home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2009 July / maximum-cd-2009-07.iso / DiscContents / Firefox Setup 3.0.7.exe / nonlocalized / chrome / browser.jar / content / browser / browser.js < prev    next >
Encoding:
Text File  |  2009-02-03  |  265.0 KB  |  7,697 lines

  1. //@line 60 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  2.  
  3. let Ci = Components.interfaces;
  4. let Cu = Components.utils;
  5. Cu.import("resource://gre/modules/XPCOMUtils.jsm");
  6.  
  7. const nsIWebNavigation = Components.interfaces.nsIWebNavigation;
  8.  
  9. const MAX_HISTORY_MENU_ITEMS = 15;
  10.  
  11. // We use this once, for Clear Private Data
  12. const GLUE_CID = "@mozilla.org/browser/browserglue;1";
  13.  
  14. var gURIFixup = null;
  15. var gCharsetMenu = null;
  16. var gLastBrowserCharset = null;
  17. var gPrevCharset = null;
  18. var gURLBar = null;
  19. var gFindBar = null;
  20. var gProxyFavIcon = null;
  21. var gNavigatorBundle = null;
  22. var gIsLoadingBlank = false;
  23. var gLastValidURLStr = "";
  24. var gMustLoadSidebar = false;
  25. var gProgressMeterPanel = null;
  26. var gProgressCollapseTimer = null;
  27. var gPrefService = null;
  28. var appCore = null;
  29. var gBrowser = null;
  30. var gNavToolbox = null;
  31. var gSidebarCommand = "";
  32. var gInPrintPreviewMode = false;
  33. let gDownloadMgr = null;
  34.  
  35. // Global variable that holds the nsContextMenu instance.
  36. var gContextMenu = null;
  37.  
  38. var gChromeState = null; // chrome state before we went into print preview
  39.  
  40. var gSanitizeListener = null;
  41.  
  42. var gAutoHideTabbarPrefListener = null;
  43. var gBookmarkAllTabsHandler = null;
  44.  
  45. //@line 106 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  46.  
  47. //@line 108 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  48. var gEditUIVisible = true;
  49. //@line 110 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  50.  
  51. /**
  52. * We can avoid adding multiple load event listeners and save some time by adding
  53. * one listener that calls all real handlers.
  54. */
  55.  
  56. function pageShowEventHandlers(event)
  57. {
  58.   // Filter out events that are not about the document load we are interested in
  59.   if (event.originalTarget == content.document) {
  60.     checkForDirectoryListing();
  61.     charsetLoadListener(event);
  62.     
  63.     XULBrowserWindow.asyncUpdateUI();
  64.   }
  65. }
  66.  
  67. /**
  68.  * Determine whether or not the content area is displaying a page with frames,
  69.  * and if so, toggle the display of the 'save frame as' menu item.
  70.  **/
  71. function getContentAreaFrameCount()
  72. {
  73.   var saveFrameItem = document.getElementById("menu_saveFrame");
  74.   if (!content || !content.frames.length || !isContentFrame(document.commandDispatcher.focusedWindow))
  75.     saveFrameItem.setAttribute("hidden", "true");
  76.   else
  77.     saveFrameItem.removeAttribute("hidden");
  78. }
  79.  
  80. function UpdateBackForwardCommands(aWebNavigation)
  81. {
  82.   var backBroadcaster = document.getElementById("Browser:Back");
  83.   var forwardBroadcaster = document.getElementById("Browser:Forward");
  84.  
  85.   // Avoid setting attributes on broadcasters if the value hasn't changed!
  86.   // Remember, guys, setting attributes on elements is expensive!  They
  87.   // get inherited into anonymous content, broadcast to other widgets, etc.!
  88.   // Don't do it if the value hasn't changed! - dwh
  89.  
  90.   var backDisabled = backBroadcaster.hasAttribute("disabled");
  91.   var forwardDisabled = forwardBroadcaster.hasAttribute("disabled");
  92.   if (backDisabled == aWebNavigation.canGoBack) {
  93.     if (backDisabled)
  94.       backBroadcaster.removeAttribute("disabled");
  95.     else
  96.       backBroadcaster.setAttribute("disabled", true);
  97.   }
  98.  
  99.   if (forwardDisabled == aWebNavigation.canGoForward) {
  100.     if (forwardDisabled)
  101.       forwardBroadcaster.removeAttribute("disabled");
  102.     else
  103.       forwardBroadcaster.setAttribute("disabled", true);
  104.   }
  105. }
  106.  
  107. //@line 253 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  108.  
  109. function BookmarkThisTab()
  110. {
  111.   var tab = getBrowser().mContextTab;
  112.   if (tab.localName != "tab")
  113.     tab = getBrowser().mCurrentTab;
  114.  
  115.   PlacesCommandHook.bookmarkPage(tab.linkedBrowser,
  116.                                  PlacesUtils.bookmarksMenuFolderId, true);
  117. }
  118.  
  119. /**
  120.  * Initialize the bookmarks toolbar and the menuitem for it.
  121.  */
  122. function initBookmarksToolbar() {
  123.   var place = PlacesUtils.getQueryStringForFolder(PlacesUtils.bookmarks.toolbarFolder);
  124.   var bt = document.getElementById("bookmarksBarContent");
  125.   if (bt)
  126.     bt.place = place;
  127.  
  128.   document.getElementById("bookmarksToolbarFolderPopup").place = place;
  129.   document.getElementById("bookmarksToolbarFolderMenu").label =
  130.     PlacesUtils.bookmarks.getItemTitle(PlacesUtils.bookmarks.toolbarFolder);
  131. }
  132.  
  133. const gSessionHistoryObserver = {
  134.   observe: function(subject, topic, data)
  135.   {
  136.     if (topic != "browser:purge-session-history")
  137.       return;
  138.  
  139.     var backCommand = document.getElementById("Browser:Back");
  140.     backCommand.setAttribute("disabled", "true");
  141.     var fwdCommand = document.getElementById("Browser:Forward");
  142.     fwdCommand.setAttribute("disabled", "true");
  143.  
  144.     if (gURLBar) {
  145.       // Clear undo history of the URL bar
  146.       gURLBar.editor.transactionManager.clear()
  147.     }
  148.   }
  149. };
  150.  
  151. /**
  152.  * Given a starting docshell and a URI to look up, find the docshell the URI
  153.  * is loaded in. 
  154.  * @param   aDocument
  155.  *          A document to find instead of using just a URI - this is more specific. 
  156.  * @param   aDocShell
  157.  *          The doc shell to start at
  158.  * @param   aSoughtURI
  159.  *          The URI that we're looking for
  160.  * @returns The doc shell that the sought URI is loaded in. Can be in 
  161.  *          subframes.
  162.  */
  163. function findChildShell(aDocument, aDocShell, aSoughtURI) {
  164.   aDocShell.QueryInterface(Components.interfaces.nsIWebNavigation);
  165.   aDocShell.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
  166.   var doc = aDocShell.getInterface(Components.interfaces.nsIDOMDocument);
  167.   if ((aDocument && doc == aDocument) || 
  168.       (aSoughtURI && aSoughtURI.spec == aDocShell.currentURI.spec))
  169.     return aDocShell;
  170.  
  171.   var node = aDocShell.QueryInterface(Components.interfaces.nsIDocShellTreeNode);
  172.   for (var i = 0; i < node.childCount; ++i) {
  173.     var docShell = node.getChildAt(i);
  174.     docShell = findChildShell(aDocument, docShell, aSoughtURI);
  175.     if (docShell)
  176.       return docShell;
  177.   }
  178.   return null;
  179. }
  180.  
  181. const gPopupBlockerObserver = {
  182.   _reportButton: null,
  183.   _kIPM: Components.interfaces.nsIPermissionManager,
  184.  
  185.   onUpdatePageReport: function (aEvent)
  186.   {
  187.     if (aEvent.originalTarget != gBrowser.selectedBrowser)
  188.       return;
  189.  
  190.     if (!this._reportButton)
  191.       this._reportButton = document.getElementById("page-report-button");
  192.  
  193.     if (!gBrowser.pageReport) {
  194.       // Hide the popup blocker statusbar button
  195.       this._reportButton.removeAttribute("blocked");
  196.  
  197.       return;
  198.     }
  199.  
  200.     this._reportButton.setAttribute("blocked", true);
  201.  
  202.     // Only show the notification again if we've not already shown it. Since
  203.     // notifications are per-browser, we don't need to worry about re-adding
  204.     // it.
  205.     if (!gBrowser.pageReport.reported) {
  206.       if (!gPrefService)
  207.         gPrefService = Components.classes["@mozilla.org/preferences-service;1"]
  208.                                  .getService(Components.interfaces.nsIPrefBranch2);
  209.       if (gPrefService.getBoolPref("privacy.popups.showBrowserMessage")) {
  210.         var bundle_browser = document.getElementById("bundle_browser");
  211.         var brandBundle = document.getElementById("bundle_brand");
  212.         var brandShortName = brandBundle.getString("brandShortName");
  213.         var message;
  214.         var popupCount = gBrowser.pageReport.length;
  215. //@line 361 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  216.         var popupButtonText = bundle_browser.getString("popupWarningButton");
  217.         var popupButtonAccesskey = bundle_browser.getString("popupWarningButton.accesskey");
  218. //@line 367 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  219.         if (popupCount > 1)
  220.           message = bundle_browser.getFormattedString("popupWarningMultiple", [brandShortName, popupCount]);
  221.         else
  222.           message = bundle_browser.getFormattedString("popupWarning", [brandShortName]);
  223.  
  224.         var notificationBox = gBrowser.getNotificationBox();
  225.         var notification = notificationBox.getNotificationWithValue("popup-blocked");
  226.         if (notification) {
  227.           notification.label = message;
  228.         }
  229.         else {
  230.           var buttons = [{
  231.             label: popupButtonText,
  232.             accessKey: popupButtonAccesskey,
  233.             popup: "blockedPopupOptions",
  234.             callback: null
  235.           }];
  236.  
  237.           const priority = notificationBox.PRIORITY_WARNING_MEDIUM;
  238.           notificationBox.appendNotification(message, "popup-blocked",
  239.                                              "chrome://browser/skin/Info.png",
  240.                                              priority, buttons);
  241.         }
  242.       }
  243.  
  244.       // Record the fact that we've reported this blocked popup, so we don't
  245.       // show it again.
  246.       gBrowser.pageReport.reported = true;
  247.     }
  248.   },
  249.  
  250.   toggleAllowPopupsForSite: function (aEvent)
  251.   {
  252.     var currentURI = gBrowser.selectedBrowser.webNavigation.currentURI;
  253.     var pm = Components.classes["@mozilla.org/permissionmanager;1"]
  254.                        .getService(this._kIPM);
  255.     var shouldBlock = aEvent.target.getAttribute("block") == "true";
  256.     var perm = shouldBlock ? this._kIPM.DENY_ACTION : this._kIPM.ALLOW_ACTION;
  257.     pm.add(currentURI, "popup", perm);
  258.  
  259.     gBrowser.getNotificationBox().removeCurrentNotification();
  260.   },
  261.  
  262.   fillPopupList: function (aEvent)
  263.   {
  264.     var bundle_browser = document.getElementById("bundle_browser");
  265.     // XXXben - rather than using |currentURI| here, which breaks down on multi-framed sites
  266.     //          we should really walk the pageReport and create a list of "allow for <host>"
  267.     //          menuitems for the common subset of hosts present in the report, this will
  268.     //          make us frame-safe.
  269.     //
  270.     // XXXjst - Note that when this is fixed to work with multi-framed sites,
  271.     //          also back out the fix for bug 343772 where
  272.     //          nsGlobalWindow::CheckOpenAllow() was changed to also
  273.     //          check if the top window's location is whitelisted.
  274.     var uri = gBrowser.selectedBrowser.webNavigation.currentURI;
  275.     var blockedPopupAllowSite = document.getElementById("blockedPopupAllowSite");
  276.     try {
  277.       blockedPopupAllowSite.removeAttribute("hidden");
  278.  
  279.       var pm = Components.classes["@mozilla.org/permissionmanager;1"]
  280.                         .getService(this._kIPM);
  281.       if (pm.testPermission(uri, "popup") == this._kIPM.ALLOW_ACTION) {
  282.         // Offer an item to block popups for this site, if a whitelist entry exists
  283.         // already for it.
  284.         var blockString = bundle_browser.getFormattedString("popupBlock", [uri.host]);
  285.         blockedPopupAllowSite.setAttribute("label", blockString);
  286.         blockedPopupAllowSite.setAttribute("block", "true");
  287.       }
  288.       else {
  289.         // Offer an item to allow popups for this site
  290.         var allowString = bundle_browser.getFormattedString("popupAllow", [uri.host]);
  291.         blockedPopupAllowSite.setAttribute("label", allowString);
  292.         blockedPopupAllowSite.removeAttribute("block");
  293.       }
  294.     }
  295.     catch (e) {
  296.       blockedPopupAllowSite.setAttribute("hidden", "true");
  297.     }
  298.  
  299.     var item = aEvent.target.lastChild;
  300.     while (item && item.getAttribute("observes") != "blockedPopupsSeparator") {
  301.       var next = item.previousSibling;
  302.       item.parentNode.removeChild(item);
  303.       item = next;
  304.     }
  305.  
  306.     var foundUsablePopupURI = false;
  307.     var pageReport = gBrowser.pageReport;
  308.     if (pageReport) {
  309.       for (var i = 0; i < pageReport.length; ++i) {
  310.         var popupURIspec = pageReport[i].popupWindowURI.spec;
  311.  
  312.         // Sometimes the popup URI that we get back from the pageReport
  313.         // isn't useful (for instance, netscape.com's popup URI ends up
  314.         // being "http://www.netscape.com", which isn't really the URI of
  315.         // the popup they're trying to show).  This isn't going to be
  316.         // useful to the user, so we won't create a menu item for it.
  317.         if (popupURIspec == "" || popupURIspec == "about:blank" ||
  318.             popupURIspec == uri.spec)
  319.           continue;
  320.  
  321.         // Because of the short-circuit above, we may end up in a situation
  322.         // in which we don't have any usable popup addresses to show in
  323.         // the menu, and therefore we shouldn't show the separator.  However,
  324.         // since we got past the short-circuit, we must've found at least
  325.         // one usable popup URI and thus we'll turn on the separator later.
  326.         foundUsablePopupURI = true;
  327.  
  328.         var menuitem = document.createElement("menuitem");
  329.         var label = bundle_browser.getFormattedString("popupShowPopupPrefix",
  330.                                                       [popupURIspec]);
  331.         menuitem.setAttribute("label", label);
  332.         menuitem.setAttribute("popupWindowURI", popupURIspec);
  333.         menuitem.setAttribute("popupWindowFeatures", pageReport[i].popupWindowFeatures);
  334.         menuitem.setAttribute("popupWindowName", pageReport[i].popupWindowName);
  335.         menuitem.setAttribute("oncommand", "gPopupBlockerObserver.showBlockedPopup(event);");
  336.         menuitem.requestingWindow = pageReport[i].requestingWindow;
  337.         menuitem.requestingDocument = pageReport[i].requestingDocument;
  338.         aEvent.target.appendChild(menuitem);
  339.       }
  340.     }
  341.  
  342.     // Show or hide the separator, depending on whether we added any
  343.     // showable popup addresses to the menu.
  344.     var blockedPopupsSeparator =
  345.       document.getElementById("blockedPopupsSeparator");
  346.     if (foundUsablePopupURI)
  347.       blockedPopupsSeparator.removeAttribute("hidden");
  348.     else
  349.       blockedPopupsSeparator.setAttribute("hidden", true);
  350.  
  351.     var blockedPopupDontShowMessage = document.getElementById("blockedPopupDontShowMessage");
  352.     var showMessage = gPrefService.getBoolPref("privacy.popups.showBrowserMessage");
  353.     blockedPopupDontShowMessage.setAttribute("checked", !showMessage);
  354.     if (aEvent.target.localName == "popup")
  355.       blockedPopupDontShowMessage.setAttribute("label", bundle_browser.getString("popupWarningDontShowFromMessage"));
  356.     else
  357.       blockedPopupDontShowMessage.setAttribute("label", bundle_browser.getString("popupWarningDontShowFromStatusbar"));
  358.   },
  359.  
  360.   showBlockedPopup: function (aEvent)
  361.   {
  362.     var target = aEvent.target;
  363.     var popupWindowURI = target.getAttribute("popupWindowURI");
  364.     var features = target.getAttribute("popupWindowFeatures");
  365.     var name = target.getAttribute("popupWindowName");
  366.  
  367.     var dwi = target.requestingWindow;
  368.  
  369.     // If we have a requesting window and the requesting document is
  370.     // still the current document, open the popup.
  371.     if (dwi && dwi.document == target.requestingDocument) {
  372.       dwi.open(popupWindowURI, name, features);
  373.     }
  374.   },
  375.  
  376.   editPopupSettings: function ()
  377.   {
  378.     var host = "";
  379.     try {
  380.       var uri = gBrowser.selectedBrowser.webNavigation.currentURI;
  381.       host = uri.host;
  382.     }
  383.     catch (e) { }
  384.  
  385.     var bundlePreferences = document.getElementById("bundle_preferences");
  386.     var params = { blockVisible   : false,
  387.                    sessionVisible : false,
  388.                    allowVisible   : true,
  389.                    prefilledHost  : host,
  390.                    permissionType : "popup",
  391.                    windowTitle    : bundlePreferences.getString("popuppermissionstitle"),
  392.                    introText      : bundlePreferences.getString("popuppermissionstext") };
  393.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  394.                         .getService(Components.interfaces.nsIWindowMediator);
  395.     var existingWindow = wm.getMostRecentWindow("Browser:Permissions");
  396.     if (existingWindow) {
  397.       existingWindow.initWithParams(params);
  398.       existingWindow.focus();
  399.     }
  400.     else
  401.       window.openDialog("chrome://browser/content/preferences/permissions.xul",
  402.                         "_blank", "resizable,dialog=no,centerscreen", params);
  403.   },
  404.  
  405.   dontShowMessage: function ()
  406.   {
  407.     var showMessage = gPrefService.getBoolPref("privacy.popups.showBrowserMessage");
  408.     var firstTime = gPrefService.getBoolPref("privacy.popups.firstTime");
  409.  
  410.     // If the info message is showing at the top of the window, and the user has never
  411.     // hidden the message before, show an info box telling the user where the info
  412.     // will be displayed.
  413.     if (showMessage && firstTime)
  414.       this._displayPageReportFirstTime();
  415.  
  416.     gPrefService.setBoolPref("privacy.popups.showBrowserMessage", !showMessage);
  417.  
  418.     gBrowser.getNotificationBox().removeCurrentNotification();
  419.   },
  420.  
  421.   _displayPageReportFirstTime: function ()
  422.   {
  423.     window.openDialog("chrome://browser/content/pageReportFirstTime.xul", "_blank",
  424.                       "dependent");
  425.   }
  426. };
  427.  
  428. const gXPInstallObserver = {
  429.   _findChildShell: function (aDocShell, aSoughtShell)
  430.   {
  431.     if (aDocShell == aSoughtShell)
  432.       return aDocShell;
  433.  
  434.     var node = aDocShell.QueryInterface(Components.interfaces.nsIDocShellTreeNode);
  435.     for (var i = 0; i < node.childCount; ++i) {
  436.       var docShell = node.getChildAt(i);
  437.       docShell = this._findChildShell(docShell, aSoughtShell);
  438.       if (docShell == aSoughtShell)
  439.         return docShell;
  440.     }
  441.     return null;
  442.   },
  443.  
  444.   _getBrowser: function (aDocShell)
  445.   {
  446.     var tabbrowser = getBrowser();
  447.     for (var i = 0; i < tabbrowser.browsers.length; ++i) {
  448.       var browser = tabbrowser.getBrowserAtIndex(i);
  449.       if (this._findChildShell(browser.docShell, aDocShell))
  450.         return browser;
  451.     }
  452.     return null;
  453.   },
  454.  
  455.   observe: function (aSubject, aTopic, aData)
  456.   {
  457.     var brandBundle = document.getElementById("bundle_brand");
  458.     var browserBundle = document.getElementById("bundle_browser");
  459.     switch (aTopic) {
  460.     case "xpinstall-install-blocked":
  461.       var installInfo = aSubject.QueryInterface(Components.interfaces.nsIXPIInstallInfo);
  462.       var win = installInfo.originatingWindow;
  463.       var shell = win.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  464.                      .getInterface(Components.interfaces.nsIWebNavigation)
  465.                      .QueryInterface(Components.interfaces.nsIDocShell);
  466.       var browser = this._getBrowser(shell);
  467.       if (browser) {
  468.         var host = installInfo.originatingURI.host;
  469.         var brandShortName = brandBundle.getString("brandShortName");
  470.         var notificationName, messageString, buttons;
  471.         if (!gPrefService.getBoolPref("xpinstall.enabled")) {
  472.           notificationName = "xpinstall-disabled"
  473.           if (gPrefService.prefIsLocked("xpinstall.enabled")) {
  474.             messageString = browserBundle.getString("xpinstallDisabledMessageLocked");
  475.             buttons = [];
  476.           }
  477.           else {
  478.             messageString = browserBundle.getFormattedString("xpinstallDisabledMessage",
  479.                                                              [brandShortName, host]);
  480.  
  481.             buttons = [{
  482.               label: browserBundle.getString("xpinstallDisabledButton"),
  483.               accessKey: browserBundle.getString("xpinstallDisabledButton.accesskey"),
  484.               popup: null,
  485.               callback: function editPrefs() {
  486.                 gPrefService.setBoolPref("xpinstall.enabled", true);
  487.                 return false;
  488.               }
  489.             }];
  490.           }
  491.         }
  492.         else {
  493.           notificationName = "xpinstall"
  494.           messageString = browserBundle.getFormattedString("xpinstallPromptWarning",
  495.                                                            [brandShortName, host]);
  496.  
  497.           buttons = [{
  498.             label: browserBundle.getString("xpinstallPromptAllowButton"),
  499.             accessKey: browserBundle.getString("xpinstallPromptAllowButton.accesskey"),
  500.             popup: null,
  501.             callback: function() {
  502.               var mgr = Components.classes["@mozilla.org/xpinstall/install-manager;1"]
  503.                                   .createInstance(Components.interfaces.nsIXPInstallManager);
  504.               mgr.initManagerWithInstallInfo(installInfo);
  505.               return false;
  506.             }
  507.           }];
  508.         }
  509.  
  510.         var notificationBox = gBrowser.getNotificationBox(browser);
  511.         if (!notificationBox.getNotificationWithValue(notificationName)) {
  512.           const priority = notificationBox.PRIORITY_WARNING_MEDIUM;
  513.           const iconURL = "chrome://mozapps/skin/update/update.png";
  514.           notificationBox.appendNotification(messageString, notificationName,
  515.                                              iconURL, priority, buttons);
  516.         }
  517.       }
  518.       break;
  519.     }
  520.   }
  521. };
  522.  
  523. function BrowserStartup()
  524. {
  525.   gBrowser = document.getElementById("content");
  526.  
  527.   var uriToLoad = null;
  528.  
  529.   // window.arguments[0]: URI to load (string), or an nsISupportsArray of
  530.   //                      nsISupportsStrings to load
  531.   //                 [1]: character set (string)
  532.   //                 [2]: referrer (nsIURI)
  533.   //                 [3]: postData (nsIInputStream)
  534.   //                 [4]: allowThirdPartyFixup (bool)
  535.   if ("arguments" in window && window.arguments[0])
  536.     uriToLoad = window.arguments[0];
  537.  
  538.   gIsLoadingBlank = uriToLoad == "about:blank";
  539.  
  540.   prepareForStartup();
  541.  
  542. //@line 694 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  543.   if (uriToLoad && !gIsLoadingBlank) {
  544.     if (uriToLoad instanceof Components.interfaces.nsISupportsArray) {
  545.       var count = uriToLoad.Count();
  546.       var specs = [];
  547.       for (var i = 0; i < count; i++) {
  548.         var urisstring = uriToLoad.GetElementAt(i).QueryInterface(Components.interfaces.nsISupportsString);
  549.         specs.push(urisstring.data);
  550.       }
  551.  
  552.       // This function throws for certain malformed URIs, so use exception handling
  553.       // so that we don't disrupt startup
  554.       try {
  555.         gBrowser.loadTabs(specs, false, true);
  556.       } catch (e) {}
  557.     }
  558.     else if (window.arguments.length >= 3) {
  559.       loadURI(uriToLoad, window.arguments[2], window.arguments[3] || null,
  560.               window.arguments[4] || false);
  561.     }
  562.     // Note: loadOneOrMoreURIs *must not* be called if window.arguments.length >= 3.
  563.     // Such callers expect that window.arguments[0] is handled as a single URI.
  564.     else
  565.       loadOneOrMoreURIs(uriToLoad);
  566.   }
  567. //@line 719 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  568.  
  569.   var sidebarSplitter;
  570.   if (window.opener && !window.opener.closed) {
  571.     var openerFindBar = window.opener.gFindBar;
  572.     if (openerFindBar && !openerFindBar.hidden &&
  573.         openerFindBar.findMode == gFindBar.FIND_NORMAL)
  574.       gFindBar.open();
  575.  
  576.     var openerSidebarBox = window.opener.document.getElementById("sidebar-box");
  577.     // If the opener had a sidebar, open the same sidebar in our window.
  578.     // The opener can be the hidden window too, if we're coming from the state
  579.     // where no windows are open, and the hidden window has no sidebar box.
  580.     if (openerSidebarBox && !openerSidebarBox.hidden) {
  581.       var sidebarBox = document.getElementById("sidebar-box");
  582.       var sidebarTitle = document.getElementById("sidebar-title");
  583.       sidebarTitle.setAttribute("value", window.opener.document.getElementById("sidebar-title").getAttribute("value"));
  584.       sidebarBox.setAttribute("width", openerSidebarBox.boxObject.width);
  585.       var sidebarCmd = openerSidebarBox.getAttribute("sidebarcommand");
  586.       sidebarBox.setAttribute("sidebarcommand", sidebarCmd);
  587.       // Note: we're setting 'src' on sidebarBox, which is a <vbox>, not on the
  588.       // <browser id="sidebar">. This lets us delay the actual load until
  589.       // delayedStartup().
  590.       sidebarBox.setAttribute("src", window.opener.document.getElementById("sidebar").getAttribute("src"));
  591.       gMustLoadSidebar = true;
  592.  
  593.       sidebarBox.hidden = false;
  594.       sidebarSplitter = document.getElementById("sidebar-splitter");
  595.       sidebarSplitter.hidden = false;
  596.       document.getElementById(sidebarCmd).setAttribute("checked", "true");
  597.     }
  598.   }
  599.   else {
  600.     var box = document.getElementById("sidebar-box");
  601.     if (box.hasAttribute("sidebarcommand")) {
  602.       var commandID = box.getAttribute("sidebarcommand");
  603.       if (commandID) {
  604.         var command = document.getElementById(commandID);
  605.         if (command) {
  606.           gMustLoadSidebar = true;
  607.           box.hidden = false;
  608.           sidebarSplitter = document.getElementById("sidebar-splitter");
  609.           sidebarSplitter.hidden = false;
  610.           command.setAttribute("checked", "true");
  611.         }
  612.         else {
  613.           // Remove the |sidebarcommand| attribute, because the element it 
  614.           // refers to no longer exists, so we should assume this sidebar
  615.           // panel has been uninstalled. (249883)
  616.           box.removeAttribute("sidebarcommand");
  617.         }
  618.       }
  619.     }
  620.   }
  621.  
  622.   // Certain kinds of automigration rely on this notification to complete their
  623.   // tasks BEFORE the browser window is shown.
  624.   var obs = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  625.   obs.notifyObservers(null, "browser-window-before-show", "");
  626.  
  627.   // Set a sane starting width/height for all resolutions on new profiles.
  628.   if (!document.documentElement.hasAttribute("width")) {
  629.     var defaultWidth = 994, defaultHeight;
  630.     if (screen.availHeight <= 600) {
  631.       document.documentElement.setAttribute("sizemode", "maximized");
  632.       defaultWidth = 610;
  633.       defaultHeight = 450;
  634.     }
  635.     else {
  636.       // Create a narrower window for large or wide-aspect displays, to suggest
  637.       // side-by-side page view.
  638.       if (screen.availWidth >= 1600)
  639.         defaultWidth = (screen.availWidth / 2) - 20;
  640.       defaultHeight = screen.availHeight - 10;
  641. //@line 797 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  642.     }
  643.     document.documentElement.setAttribute("width", defaultWidth);
  644.     document.documentElement.setAttribute("height", defaultHeight);
  645.   }
  646.  
  647.   if (gURLBar && document.documentElement.getAttribute("chromehidden").indexOf("toolbar") != -1) {
  648.  
  649.     gURLBar.setAttribute("readonly", "true");
  650.     gURLBar.setAttribute("enablehistory", "false");
  651.   }
  652.  
  653.   setTimeout(delayedStartup, 0);
  654. }
  655.  
  656. function HandleAppCommandEvent(evt)
  657. {
  658.   evt.stopPropagation();
  659.   switch (evt.command) {
  660.   case "Back":
  661.     BrowserBack();
  662.     break;
  663.   case "Forward":
  664.     BrowserForward();
  665.     break;
  666.   case "Reload":
  667.     BrowserReloadSkipCache();
  668.     break;
  669.   case "Stop":
  670.     BrowserStop();
  671.     break;
  672.   case "Search":
  673.     BrowserSearch.webSearch();
  674.     break;
  675.   case "Bookmarks":
  676.     toggleSidebar('viewBookmarksSidebar');
  677.     break;
  678.   case "Home":
  679.     BrowserHome();
  680.     break;
  681.   default:
  682.     break;
  683.   }
  684. }
  685.  
  686. function prepareForStartup()
  687. {
  688.   gURLBar = document.getElementById("urlbar");
  689.   gNavigatorBundle = document.getElementById("bundle_browser");
  690.   gProgressMeterPanel = document.getElementById("statusbar-progresspanel");
  691.   gFindBar = document.getElementById("FindToolbar");
  692.   gBrowser.addEventListener("DOMUpdatePageReport", gPopupBlockerObserver.onUpdatePageReport, false);
  693.   // Note: we need to listen to untrusted events, because the pluginfinder XBL
  694.   // binding can't fire trusted ones (runs with page privileges).
  695.   gBrowser.addEventListener("PluginNotFound", gMissingPluginInstaller.newMissingPlugin, true, true);
  696.   gBrowser.addEventListener("PluginBlocklisted", gMissingPluginInstaller.newMissingPlugin, true, true);
  697.   gBrowser.addEventListener("NewPluginInstalled", gMissingPluginInstaller.refreshBrowser, false);
  698.   gBrowser.addEventListener("NewTab", BrowserOpenTab, false);
  699.   window.addEventListener("AppCommand", HandleAppCommandEvent, true);
  700.  
  701.   var webNavigation;
  702.   try {
  703.     // Create the browser instance component.
  704.     appCore = Components.classes["@mozilla.org/appshell/component/browser/instance;1"]
  705.                         .createInstance(Components.interfaces.nsIBrowserInstance);
  706.     if (!appCore)
  707.       throw "couldn't create a browser instance";
  708.  
  709.     webNavigation = getWebNavigation();
  710.     if (!webNavigation)
  711.       throw "no XBL binding for browser";
  712.   } catch (e) {
  713.     alert("Error launching browser window:" + e);
  714.     window.close(); // Give up.
  715.     return;
  716.   }
  717.  
  718.   // initialize observers and listeners
  719.   // and give C++ access to gBrowser
  720.   window.XULBrowserWindow = new nsBrowserStatusHandler();
  721.   window.QueryInterface(Ci.nsIInterfaceRequestor)
  722.         .getInterface(nsIWebNavigation)
  723.         .QueryInterface(Ci.nsIDocShellTreeItem).treeOwner
  724.         .QueryInterface(Ci.nsIInterfaceRequestor)
  725.         .getInterface(Ci.nsIXULWindow)
  726.         .XULBrowserWindow = window.XULBrowserWindow;
  727.   window.QueryInterface(Ci.nsIDOMChromeWindow).browserDOMWindow =
  728.     new nsBrowserAccess();
  729.  
  730.   // set default character set if provided
  731.   if ("arguments" in window && window.arguments.length > 1 && window.arguments[1]) {
  732.     if (window.arguments[1].indexOf("charset=") != -1) {
  733.       var arrayArgComponents = window.arguments[1].split("=");
  734.       if (arrayArgComponents) {
  735.         //we should "inherit" the charset menu setting in a new window
  736.         getMarkupDocumentViewer().defaultCharacterSet = arrayArgComponents[1];
  737.       }
  738.     }
  739.   }
  740.  
  741.   // Initialize browser instance..
  742.   appCore.setWebShellWindow(window);
  743.  
  744.   // Manually hook up session and global history for the first browser
  745.   // so that we don't have to load global history before bringing up a
  746.   // window.
  747.   // Wire up session and global history before any possible
  748.   // progress notifications for back/forward button updating
  749.   webNavigation.sessionHistory = Components.classes["@mozilla.org/browser/shistory;1"]
  750.                                            .createInstance(Components.interfaces.nsISHistory);
  751.   var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  752.   os.addObserver(gBrowser.browsers[0], "browser:purge-session-history", false);
  753.  
  754.   // remove the disablehistory attribute so the browser cleans up, as
  755.   // though it had done this work itself
  756.   gBrowser.browsers[0].removeAttribute("disablehistory");
  757.  
  758.   // enable global history
  759.   gBrowser.docShell.QueryInterface(Components.interfaces.nsIDocShellHistory).useGlobalHistory = true;
  760.  
  761.   // hook up UI through progress listener
  762.   gBrowser.addProgressListener(window.XULBrowserWindow, Components.interfaces.nsIWebProgress.NOTIFY_ALL);
  763.  
  764.   // setup our common DOMLinkAdded listener
  765.   gBrowser.addEventListener("DOMLinkAdded", DOMLinkHandler, false);
  766. }
  767.  
  768. function delayedStartup()
  769. {
  770.   var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  771.   os.addObserver(gSessionHistoryObserver, "browser:purge-session-history", false);
  772.   os.addObserver(gXPInstallObserver, "xpinstall-install-blocked", false);
  773.  
  774.   if (!gPrefService)
  775.     gPrefService = Components.classes["@mozilla.org/preferences-service;1"]
  776.                              .getService(Components.interfaces.nsIPrefBranch2);
  777.   BrowserOffline.init();
  778.   OfflineApps.init();
  779.  
  780.   gBrowser.addEventListener("pageshow", function(evt) { setTimeout(pageShowEventHandlers, 0, evt); }, true);
  781.  
  782.   window.addEventListener("keypress", onBrowserKeyPress, false);
  783.  
  784.   // Ensure login manager is up and running.
  785.   Cc["@mozilla.org/login-manager;1"].getService(Ci.nsILoginManager);
  786.  
  787.   if (gMustLoadSidebar) {
  788.     var sidebar = document.getElementById("sidebar");
  789.     var sidebarBox = document.getElementById("sidebar-box");
  790.     sidebar.setAttribute("src", sidebarBox.getAttribute("src"));
  791.   }
  792.  
  793.   UpdateUrlbarSearchSplitterState();
  794.   
  795.   try {
  796.     placesMigrationTasks();
  797.   } catch(ex) {}
  798.   initBookmarksToolbar();
  799.   PlacesStarButton.init();
  800.  
  801.   // called when we go into full screen, even if it is
  802.   // initiated by a web page script
  803.   window.addEventListener("fullscreen", onFullScreen, true);
  804.  
  805.   if (gIsLoadingBlank && gURLBar && isElementVisible(gURLBar))
  806.     focusElement(gURLBar);
  807.   else
  808.     focusElement(content);
  809.  
  810.   var navToolbox = getNavToolbox();
  811.   navToolbox.customizeDone = BrowserToolboxCustomizeDone;
  812.   navToolbox.customizeChange = BrowserToolboxCustomizeChange;
  813.  
  814.   // Set up Sanitize Item
  815.   gSanitizeListener = new SanitizeListener();
  816.  
  817.   // Enable/Disable auto-hide tabbar
  818.   gAutoHideTabbarPrefListener = new AutoHideTabbarPrefListener();
  819.   gPrefService.addObserver(gAutoHideTabbarPrefListener.domain,
  820.                            gAutoHideTabbarPrefListener, false);
  821.  
  822.   gPrefService.addObserver(gHomeButton.prefDomain, gHomeButton, false);
  823.  
  824.   var homeButton = document.getElementById("home-button");
  825.   gHomeButton.updateTooltip(homeButton);
  826.   gHomeButton.updatePersonalToolbarStyle(homeButton);
  827.  
  828. //@line 984 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  829.   // Perform default browser checking (after window opens).
  830.   var shell = getShellService();
  831.   if (shell) {
  832.     var shouldCheck = shell.shouldCheckDefaultBrowser;
  833.     var willRecoverSession = false;
  834.     try {
  835.       var ss = Cc["@mozilla.org/browser/sessionstartup;1"].
  836.                getService(Ci.nsISessionStartup);
  837.       willRecoverSession =
  838.         (ss.sessionType == Ci.nsISessionStartup.RECOVER_SESSION);
  839.     }
  840.     catch (ex) { /* never mind; suppose SessionStore is broken */ }
  841.     if (shouldCheck && !shell.isDefaultBrowser(true) && !willRecoverSession) {
  842.       var brandBundle = document.getElementById("bundle_brand");
  843.       var shellBundle = document.getElementById("bundle_shell");
  844.  
  845.       var brandShortName = brandBundle.getString("brandShortName");
  846.       var promptTitle = shellBundle.getString("setDefaultBrowserTitle");
  847.       var promptMessage = shellBundle.getFormattedString("setDefaultBrowserMessage",
  848.                                                          [brandShortName]);
  849.       var checkboxLabel = shellBundle.getFormattedString("setDefaultBrowserDontAsk",
  850.                                                          [brandShortName]);
  851.       const IPS = Components.interfaces.nsIPromptService;
  852.       var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
  853.                                                 .getService(IPS);
  854.       var checkEveryTime = { value: shouldCheck };
  855.       var rv = ps.confirmEx(window, promptTitle, promptMessage,
  856.                             IPS.STD_YES_NO_BUTTONS,
  857.                             null, null, null, checkboxLabel, checkEveryTime);
  858.       if (rv == 0)
  859.         shell.setDefaultBrowser(true, false);
  860.       shell.shouldCheckDefaultBrowser = checkEveryTime.value;
  861.     }
  862.   }
  863. //@line 1019 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  864.  
  865.   // BiDi UI
  866.   gBidiUI = isBidiEnabled();
  867.   if (gBidiUI) {
  868.     document.getElementById("documentDirection-separator").hidden = false;
  869.     document.getElementById("documentDirection-swap").hidden = false;
  870.     document.getElementById("textfieldDirection-separator").hidden = false;
  871.     document.getElementById("textfieldDirection-swap").hidden = false;
  872.   }
  873.  
  874. //@line 1035 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  875.  
  876.   // Initialize the microsummary service by retrieving it, prompting its factory
  877.   // to create its singleton, whose constructor initializes the service.
  878.   try {
  879.     Cc["@mozilla.org/microsummary/service;1"].getService(Ci.nsIMicrosummaryService);
  880.   } catch (ex) {
  881.     Components.utils.reportError("Failed to init microsummary service:\n" + ex);
  882.   }
  883.  
  884.   // Initialize the full zoom setting.
  885.   // We do this before the session restore service gets initialized so we can
  886.   // apply full zoom settings to tabs restored by the session restore service.
  887.   try {
  888.     FullZoom.init();
  889.   }
  890.   catch(ex) {
  891.     Components.utils.reportError("Failed to init content pref service:\n" + ex);
  892.   }
  893.  
  894. //@line 1055 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  895.   // For Vista, flip the default download folder pref once from Desktop to Downloads
  896.   // on new profiles.
  897.   try {
  898.     var sysInfo = Cc["@mozilla.org/system-info;1"].
  899.                   getService(Ci.nsIPropertyBag2);
  900.     if (parseFloat(sysInfo.getProperty("version")) >= 6 &&
  901.         !gPrefService.getPrefType("browser.download.dir") &&
  902.         gPrefService.getIntPref("browser.download.folderList") == 0) {
  903.       var dnldMgr = Cc["@mozilla.org/download-manager;1"]
  904.                               .getService(Ci.nsIDownloadManager);
  905.       gPrefService.setCharPref("browser.download.dir", 
  906.         dnldMgr.defaultDownloadsDirectory.path);
  907.       gPrefService.setIntPref("browser.download.folderList", 1);
  908.     }
  909.   } catch (ex) {
  910.   }
  911. //@line 1072 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  912.  
  913.   // initialize the session-restore service (in case it's not already running)
  914.   if (document.documentElement.getAttribute("windowtype") == "navigator:browser") {
  915.     try {
  916.       var ss = Cc["@mozilla.org/browser/sessionstore;1"].
  917.                getService(Ci.nsISessionStore);
  918.       ss.init(window);
  919.     } catch(ex) {
  920.       dump("nsSessionStore could not be initialized: " + ex + "\n");
  921.     }
  922.   }
  923.  
  924.   // bookmark-all-tabs command
  925.   gBookmarkAllTabsHandler = new BookmarkAllTabsHandler();
  926.  
  927.   // Attach a listener to watch for "command" events bubbling up from error
  928.   // pages.  This lets us fix bugs like 401575 which require error page UI to
  929.   // do privileged things, without letting error pages have any privilege
  930.   // themselves.
  931.   gBrowser.addEventListener("command", BrowserOnCommand, false);
  932.  
  933.   // Delayed initialization of the livemarks update timer.
  934.   // Livemark updates don't need to start until after bookmark UI 
  935.   // such as the toolbar has initialized. Starting 5 seconds after
  936.   // delayedStartup in order to stagger this before the download
  937.   // manager starts (see below).
  938.   setTimeout(function() PlacesUtils.livemarks.start(), 5000);
  939.  
  940.   // Initialize the download manager some time after the app starts so that
  941.   // auto-resume downloads begin (such as after crashing or quitting with
  942.   // active downloads) and speeds up the first-load of the download manager UI.
  943.   // If the user manually opens the download manager before the timeout, the
  944.   // downloads will start right away, and getting the service again won't hurt.
  945.   setTimeout(function() {
  946.     gDownloadMgr = Cc["@mozilla.org/download-manager;1"].
  947.                    getService(Ci.nsIDownloadManager);
  948.  
  949.     // Initialize the downloads monitor panel listener
  950.     DownloadMonitorPanel.init();
  951.   }, 10000);
  952.  
  953. //@line 1114 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  954.   updateEditUIVisibility();
  955.   let placesContext = document.getElementById("placesContext");
  956.   placesContext.addEventListener("popupshowing", updateEditUIVisibility, false);
  957.   placesContext.addEventListener("popuphiding", updateEditUIVisibility, false);
  958. //@line 1119 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  959. }
  960.  
  961. function BrowserShutdown()
  962. {
  963.   try {
  964.     FullZoom.destroy();
  965.   }
  966.   catch(ex) {
  967.     Components.utils.reportError(ex);
  968.   }
  969.  
  970.   var os = Components.classes["@mozilla.org/observer-service;1"]
  971.     .getService(Components.interfaces.nsIObserverService);
  972.   os.removeObserver(gSessionHistoryObserver, "browser:purge-session-history");
  973.   os.removeObserver(gXPInstallObserver, "xpinstall-install-blocked");
  974.  
  975.   try {
  976.     gBrowser.removeProgressListener(window.XULBrowserWindow);
  977.   } catch (ex) {
  978.   }
  979.  
  980.   PlacesStarButton.uninit();
  981.  
  982.   try {
  983.     gPrefService.removeObserver(gAutoHideTabbarPrefListener.domain,
  984.                                 gAutoHideTabbarPrefListener);
  985.     gPrefService.removeObserver(gHomeButton.prefDomain, gHomeButton);
  986.   } catch (ex) {
  987.     Components.utils.reportError(ex);
  988.   }
  989.  
  990.   if (gSanitizeListener)
  991.     gSanitizeListener.shutdown();
  992.  
  993.   BrowserOffline.uninit();
  994.   OfflineApps.uninit();
  995.   DownloadMonitorPanel.uninit();
  996.  
  997.   var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
  998.   var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
  999.   var enumerator = windowManagerInterface.getEnumerator(null);
  1000.   enumerator.getNext();
  1001.   if (!enumerator.hasMoreElements()) {
  1002.     document.persist("sidebar-box", "sidebarcommand");
  1003.     document.persist("sidebar-box", "width");
  1004.     document.persist("sidebar-box", "src");
  1005.     document.persist("sidebar-title", "value");
  1006.   }
  1007.  
  1008.   window.XULBrowserWindow.destroy();
  1009.   window.XULBrowserWindow = null;
  1010.   window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  1011.         .getInterface(Components.interfaces.nsIWebNavigation)
  1012.         .QueryInterface(Components.interfaces.nsIDocShellTreeItem).treeOwner
  1013.         .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  1014.         .getInterface(Components.interfaces.nsIXULWindow)
  1015.         .XULBrowserWindow = null;
  1016.   window.QueryInterface(Ci.nsIDOMChromeWindow).browserDOMWindow = null;
  1017.  
  1018.   // Close the app core.
  1019.   if (appCore)
  1020.     appCore.close();
  1021. }
  1022.  
  1023. //@line 1250 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  1024.  
  1025. function AutoHideTabbarPrefListener()
  1026. {
  1027.   this.toggleAutoHideTabbar();
  1028. }
  1029.  
  1030. AutoHideTabbarPrefListener.prototype =
  1031. {
  1032.   domain: "browser.tabs.autoHide",
  1033.   observe: function (aSubject, aTopic, aPrefName)
  1034.   {
  1035.     if (aTopic != "nsPref:changed" || aPrefName != this.domain)
  1036.       return;
  1037.  
  1038.     this.toggleAutoHideTabbar();
  1039.   },
  1040.  
  1041.   toggleAutoHideTabbar: function ()
  1042.   {
  1043.     if (gBrowser.tabContainer.childNodes.length == 1 &&
  1044.         window.toolbar.visible) {
  1045.       var aVisible = false;
  1046.       try {
  1047.         aVisible = !gPrefService.getBoolPref(this.domain);
  1048.       }
  1049.       catch (e) {
  1050.       }
  1051.       gBrowser.setStripVisibilityTo(aVisible);
  1052.       gPrefService.setBoolPref("browser.tabs.forceHide", false);
  1053.     }
  1054.   }
  1055. }
  1056.  
  1057. function SanitizeListener()
  1058. {
  1059.   gPrefService.addObserver(this.promptDomain, this, false);
  1060.  
  1061.   this._defaultLabel = document.getElementById("sanitizeItem")
  1062.                                .getAttribute("label");
  1063.   this._updateSanitizeItem();
  1064.  
  1065.   if (gPrefService.prefHasUserValue(this.didSanitizeDomain)) {
  1066.     gPrefService.clearUserPref(this.didSanitizeDomain);
  1067.     // We need to persist this preference change, since we want to
  1068.     // check it at next app start even if the browser exits abruptly
  1069.     gPrefService.QueryInterface(Ci.nsIPrefService).savePrefFile(null);
  1070.   }
  1071. }
  1072.  
  1073. SanitizeListener.prototype =
  1074. {
  1075.   promptDomain      : "privacy.sanitize.promptOnSanitize",
  1076.   didSanitizeDomain : "privacy.sanitize.didShutdownSanitize",
  1077.  
  1078.   observe: function (aSubject, aTopic, aPrefName)
  1079.   {
  1080.     this._updateSanitizeItem();
  1081.   },
  1082.  
  1083.   shutdown: function ()
  1084.   {
  1085.     gPrefService.removeObserver(this.promptDomain, this);
  1086.   },
  1087.  
  1088.   _updateSanitizeItem: function ()
  1089.   {
  1090.     var label = gPrefService.getBoolPref(this.promptDomain) ?
  1091.         gNavigatorBundle.getString("sanitizeWithPromptLabel") : 
  1092.         this._defaultLabel;
  1093.     document.getElementById("sanitizeItem").setAttribute("label", label);
  1094.   }
  1095. }
  1096.  
  1097. function onBrowserKeyPress(event)
  1098. {
  1099.   if (event.altKey && event.keyCode == KeyEvent.DOM_VK_RETURN) {
  1100.     // XXXblake Proper fix is to just check whether focus is in the urlbar. However, focus with the autocomplete widget is all
  1101.     // hacky and broken and there's no way to do that right now. So this just patches it to ensure that alt+enter works when focus
  1102.     // is on a link.
  1103.     if (!(document.commandDispatcher.focusedElement instanceof HTMLAnchorElement)) {
  1104.       // Don't let winxp beep on ALT+ENTER, since the URL bar uses it.
  1105.       event.preventDefault();
  1106.       return;
  1107.     }
  1108.   }
  1109. }
  1110.  
  1111. function BrowserNumberTabSelection(event, index)
  1112. {
  1113.   // [Ctrl]+[9] always selects the last tab
  1114.   if (index == 8)
  1115.     index = gBrowser.tabContainer.childNodes.length - 1;
  1116.   else if (index >= gBrowser.tabContainer.childNodes.length)
  1117.     return;
  1118.  
  1119.   var oldTab = gBrowser.selectedTab;
  1120.   var newTab = gBrowser.tabContainer.childNodes[index];
  1121.   if (newTab != oldTab)
  1122.     gBrowser.selectedTab = newTab;
  1123.  
  1124.   event.preventDefault();
  1125.   event.stopPropagation();
  1126. }
  1127.  
  1128. function gotoHistoryIndex(aEvent)
  1129. {
  1130.   var index = aEvent.target.getAttribute("index");
  1131.   if (!index)
  1132.     return false;
  1133.  
  1134.   var where = whereToOpenLink(aEvent);
  1135.  
  1136.   if (where == "current") {
  1137.     // Normal click.  Go there in the current tab and update session history.
  1138.  
  1139.     try {
  1140.       getBrowser().gotoIndex(index);
  1141.     }
  1142.     catch(ex) {
  1143.       return false;
  1144.     }
  1145.     return true;
  1146.   }
  1147.   else {
  1148.     // Modified click.  Go there in a new tab/window.
  1149.     // This code doesn't copy history or work well with framed pages.
  1150.  
  1151.     var sessionHistory = getWebNavigation().sessionHistory;
  1152.     var entry = sessionHistory.getEntryAtIndex(index, false);
  1153.     var url = entry.URI.spec;
  1154.     openUILinkIn(url, where);
  1155.     return true;
  1156.   }
  1157. }
  1158.  
  1159. function BrowserForward(aEvent, aIgnoreAlt)
  1160. {
  1161.   var where = whereToOpenLink(aEvent, false, aIgnoreAlt);
  1162.  
  1163.   if (where == "current") {
  1164.     try {
  1165.       getBrowser().goForward();
  1166.     }
  1167.     catch(ex) {
  1168.     }
  1169.   }
  1170.   else {
  1171.     var sessionHistory = getWebNavigation().sessionHistory;
  1172.     var currentIndex = sessionHistory.index;
  1173.     var entry = sessionHistory.getEntryAtIndex(currentIndex + 1, false);
  1174.     var url = entry.URI.spec;
  1175.     openUILinkIn(url, where);
  1176.   }
  1177. }
  1178.  
  1179. function BrowserBack(aEvent, aIgnoreAlt)
  1180. {
  1181.   var where = whereToOpenLink(aEvent, false, aIgnoreAlt);
  1182.  
  1183.   if (where == "current") {
  1184.     try {
  1185.       getBrowser().goBack();
  1186.     }
  1187.     catch(ex) {
  1188.     }
  1189.   }
  1190.   else {
  1191.     var sessionHistory = getWebNavigation().sessionHistory;
  1192.     var currentIndex = sessionHistory.index;
  1193.     var entry = sessionHistory.getEntryAtIndex(currentIndex - 1, false);
  1194.     var url = entry.URI.spec;
  1195.     openUILinkIn(url, where);
  1196.   }
  1197. }
  1198.  
  1199. function BrowserHandleBackspace()
  1200. {
  1201.   switch (gPrefService.getIntPref("browser.backspace_action")) {
  1202.   case 0:
  1203.     BrowserBack();
  1204.     break;
  1205.   case 1:
  1206.     goDoCommand("cmd_scrollPageUp");
  1207.     break;
  1208.   }
  1209. }
  1210.  
  1211. function BrowserHandleShiftBackspace()
  1212. {
  1213.   switch (gPrefService.getIntPref("browser.backspace_action")) {
  1214.   case 0:
  1215.     BrowserForward();
  1216.     break;
  1217.   case 1:
  1218.     goDoCommand("cmd_scrollPageDown");
  1219.     break;
  1220.   }
  1221. }
  1222.  
  1223. function BrowserStop()
  1224. {
  1225.   try {
  1226.     const stopFlags = nsIWebNavigation.STOP_ALL;
  1227.     getWebNavigation().stop(stopFlags);
  1228.   }
  1229.   catch(ex) {
  1230.   }
  1231. }
  1232.  
  1233. function BrowserReload()
  1234. {
  1235.   const reloadFlags = nsIWebNavigation.LOAD_FLAGS_NONE;
  1236.   return BrowserReloadWithFlags(reloadFlags);
  1237. }
  1238.  
  1239. function BrowserReloadSkipCache()
  1240. {
  1241.   // Bypass proxy and cache.
  1242.   const reloadFlags = nsIWebNavigation.LOAD_FLAGS_BYPASS_PROXY | nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE;
  1243.   return BrowserReloadWithFlags(reloadFlags);
  1244. }
  1245.  
  1246. function BrowserHome()
  1247. {
  1248.   var homePage = gHomeButton.getHomePage();
  1249.   loadOneOrMoreURIs(homePage);
  1250. }
  1251.  
  1252. function BrowserGoHome(aEvent)
  1253. {
  1254.   if (aEvent && "button" in aEvent &&
  1255.       aEvent.button == 2) // right-click: do nothing
  1256.     return;
  1257.  
  1258.   var homePage = gHomeButton.getHomePage();
  1259.   var where = whereToOpenLink(aEvent);
  1260.   var urls;
  1261.  
  1262.   // openUILinkIn in utilityOverlay.js doesn't handle loading multiple pages
  1263.   switch (where) {
  1264.   case "save":
  1265.     urls = homePage.split("|");
  1266.     saveURL(urls[0], null, null, true);  // only save the first page
  1267.     break;
  1268.   case "current":
  1269.     loadOneOrMoreURIs(homePage);
  1270.     break;
  1271.   case "tabshifted":
  1272.   case "tab":
  1273.     urls = homePage.split("|");
  1274.     var loadInBackground = getBoolPref("browser.tabs.loadBookmarksInBackground", false);
  1275.     gBrowser.loadTabs(urls, loadInBackground);
  1276.     break;
  1277.   case "window":
  1278.     OpenBrowserWindow();
  1279.     break;
  1280.   }
  1281. }
  1282.  
  1283. function loadOneOrMoreURIs(aURIString)
  1284. {
  1285. //@line 1519 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  1286.   // This function throws for certain malformed URIs, so use exception handling
  1287.   // so that we don't disrupt startup
  1288.   try {
  1289.     gBrowser.loadTabs(aURIString.split("|"), false, true);
  1290.   } 
  1291.   catch (e) {
  1292.   }
  1293. }
  1294.  
  1295. function focusAndSelectUrlBar()
  1296. {
  1297.   if (gURLBar && isElementVisible(gURLBar) && !gURLBar.readOnly) {
  1298.     gURLBar.focus();
  1299.     gURLBar.select();
  1300.     return true;
  1301.   }
  1302.   return false;
  1303. }
  1304.  
  1305. function openLocation()
  1306. {
  1307.   if (window.fullScreen)
  1308.     FullScreen.mouseoverToggle(true);
  1309.  
  1310.   if (focusAndSelectUrlBar())
  1311.     return;
  1312. //@line 1562 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  1313.   openDialog("chrome://browser/content/openLocation.xul", "_blank",
  1314.              "chrome,modal,titlebar", window);
  1315. }
  1316.  
  1317. function openLocationCallback()
  1318. {
  1319.   // make sure the DOM is ready
  1320.   setTimeout(function() { this.openLocation(); }, 0);
  1321. }
  1322.  
  1323. function BrowserOpenTab()
  1324. {
  1325.   if (!gBrowser) {
  1326.     // If there are no open browser windows, open a new one
  1327.     window.openDialog("chrome://browser/content/", "_blank",
  1328.                       "chrome,all,dialog=no", "about:blank");
  1329.     return;
  1330.   }
  1331.   gBrowser.loadOneTab("about:blank", null, null, null, false, false);
  1332.   if (gURLBar)
  1333.     gURLBar.focus();
  1334. }
  1335.  
  1336. /* Called from the openLocation dialog. This allows that dialog to instruct
  1337.    its opener to open a new window and then step completely out of the way.
  1338.    Anything less byzantine is causing horrible crashes, rather believably,
  1339.    though oddly only on Linux. */
  1340. function delayedOpenWindow(chrome, flags, href, postData)
  1341. {
  1342.   // The other way to use setTimeout,
  1343.   // setTimeout(openDialog, 10, chrome, "_blank", flags, url),
  1344.   // doesn't work here.  The extra "magic" extra argument setTimeout adds to
  1345.   // the callback function would confuse prepareForStartup() by making
  1346.   // window.arguments[1] be an integer instead of null.
  1347.   setTimeout(function() { openDialog(chrome, "_blank", flags, href, null, null, postData); }, 10);
  1348. }
  1349.  
  1350. /* Required because the tab needs time to set up its content viewers and get the load of
  1351.    the URI kicked off before becoming the active content area. */
  1352. function delayedOpenTab(aUrl, aReferrer, aCharset, aPostData, aAllowThirdPartyFixup)
  1353. {
  1354.   gBrowser.loadOneTab(aUrl, aReferrer, aCharset, aPostData, false, aAllowThirdPartyFixup);
  1355. }
  1356.  
  1357. function BrowserOpenFileWindow()
  1358. {
  1359.   // Get filepicker component.
  1360.   try {
  1361.     const nsIFilePicker = Components.interfaces.nsIFilePicker;
  1362.     var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  1363.     fp.init(window, gNavigatorBundle.getString("openFile"), nsIFilePicker.modeOpen);
  1364.     fp.appendFilters(nsIFilePicker.filterAll | nsIFilePicker.filterText | nsIFilePicker.filterImages |
  1365.                      nsIFilePicker.filterXML | nsIFilePicker.filterHTML);
  1366.  
  1367.     if (fp.show() == nsIFilePicker.returnOK)
  1368.       openTopWin(fp.fileURL.spec);
  1369.   } catch (ex) {
  1370.   }
  1371. }
  1372.  
  1373. function BrowserCloseTabOrWindow()
  1374. {
  1375. //@line 1631 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  1376.  
  1377.   if (gBrowser.tabContainer.childNodes.length > 1) {
  1378.     gBrowser.removeCurrentTab(); 
  1379.     return;
  1380.   }
  1381.  
  1382. //@line 1638 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  1383.   if (gBrowser.localName == "tabbrowser" && window.toolbar.visible &&
  1384.       !gPrefService.getBoolPref("browser.tabs.autoHide")) {
  1385.     // Replace the remaining tab with a blank one and focus the address bar
  1386.     gBrowser.removeCurrentTab();
  1387.     if (gURLBar)
  1388.       setTimeout(function() { gURLBar.focus(); }, 0);
  1389.     return;
  1390.   }
  1391. //@line 1647 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  1392.  
  1393.   closeWindow(true);
  1394. }
  1395.  
  1396. function BrowserTryToCloseWindow()
  1397. {
  1398.   if (WindowIsClosing()) {
  1399.     if (window.fullScreen) {
  1400.       gBrowser.mPanelContainer.removeEventListener("mousemove",
  1401.                                                    FullScreen._collapseCallback, false);
  1402.       document.removeEventListener("keypress", FullScreen._keyToggleCallback, false);
  1403.       document.removeEventListener("popupshown", FullScreen._setPopupOpen, false);
  1404.       document.removeEventListener("popuphidden", FullScreen._setPopupOpen, false);
  1405.       gPrefService.removeObserver("browser.fullscreen", FullScreen);
  1406.  
  1407.       var fullScrToggler = document.getElementById("fullscr-toggler");
  1408.       if (fullScrToggler) {
  1409.         fullScrToggler.removeEventListener("mouseover", FullScreen._expandCallback, false);
  1410.         fullScrToggler.removeEventListener("dragenter", FullScreen._expandCallback, false);
  1411.       }
  1412.     }
  1413.  
  1414.     window.close();     // WindowIsClosing does all the necessary checks
  1415.   }
  1416. }
  1417.  
  1418. function loadURI(uri, referrer, postData, allowThirdPartyFixup)
  1419. {
  1420.   try {
  1421.     if (postData === undefined)
  1422.       postData = null;
  1423.     var flags = nsIWebNavigation.LOAD_FLAGS_NONE;
  1424.     if (allowThirdPartyFixup) {
  1425.       flags = nsIWebNavigation.LOAD_FLAGS_ALLOW_THIRD_PARTY_FIXUP;
  1426.     }
  1427.     getBrowser().loadURIWithFlags(uri, flags, referrer, null, postData);
  1428.   } catch (e) {
  1429.   }
  1430. }
  1431.  
  1432. function BrowserLoadURL(aTriggeringEvent, aPostData) {
  1433.   var url = gURLBar.value;
  1434.  
  1435.   if (aTriggeringEvent instanceof MouseEvent) {
  1436.     if (aTriggeringEvent.button == 2)
  1437.       return; // Do nothing for right clicks
  1438.  
  1439.     // We have a mouse event (from the go button), so use the standard
  1440.     // UI link behaviors
  1441.     openUILink(url, aTriggeringEvent, false, false,
  1442.                true /* allow third party fixup */, aPostData);
  1443.     return;
  1444.   }
  1445.  
  1446.   if (aTriggeringEvent && aTriggeringEvent.altKey) {
  1447.     handleURLBarRevert();
  1448.     content.focus();
  1449.     gBrowser.loadOneTab(url, null, null, aPostData, false,
  1450.                         true /* allow third party fixup */);
  1451.     aTriggeringEvent.preventDefault();
  1452.     aTriggeringEvent.stopPropagation();
  1453.   }
  1454.   else
  1455.     loadURI(url, null, aPostData, true /* allow third party fixup */);
  1456.  
  1457.   focusElement(content);
  1458. }
  1459.  
  1460. function getShortcutOrURI(aURL, aPostDataRef) {
  1461.   var shortcutURL = null;
  1462.   var keyword = aURL;
  1463.   var param = "";
  1464.   var searchService = Cc["@mozilla.org/browser/search-service;1"].
  1465.                       getService(Ci.nsIBrowserSearchService);
  1466.  
  1467.   var offset = aURL.indexOf(" ");
  1468.   if (offset > 0) {
  1469.     keyword = aURL.substr(0, offset);
  1470.     param = aURL.substr(offset + 1);
  1471.   }
  1472.  
  1473.   if (!aPostDataRef)
  1474.     aPostDataRef = {};
  1475.  
  1476.   var engine = searchService.getEngineByAlias(keyword);
  1477.   if (engine) {
  1478.     var submission = engine.getSubmission(param, null);
  1479.     aPostDataRef.value = submission.postData;
  1480.     return submission.uri.spec;
  1481.   }
  1482.  
  1483.   [shortcutURL, aPostDataRef.value] =
  1484.     PlacesUtils.getURLAndPostDataForKeyword(keyword);
  1485.  
  1486.   if (!shortcutURL)
  1487.     return aURL;
  1488.  
  1489.   var postData = "";
  1490.   if (aPostDataRef.value)
  1491.     postData = unescape(aPostDataRef.value);
  1492.  
  1493.   if (/%s/i.test(shortcutURL) || /%s/i.test(postData)) {
  1494.     var charset = "";
  1495.     const re = /^(.*)\&mozcharset=([a-zA-Z][_\-a-zA-Z0-9]+)\s*$/;
  1496.     var matches = shortcutURL.match(re);
  1497.     if (matches)
  1498.       [, shortcutURL, charset] = matches;
  1499.     else {
  1500.       // Try to get the saved character-set.
  1501.       try {
  1502.         // makeURI throws if URI is invalid.
  1503.         // Will return an empty string if character-set is not found.
  1504.         charset = PlacesUtils.history.getCharsetForURI(makeURI(shortcutURL));
  1505.       } catch (e) {}
  1506.     }
  1507.  
  1508.     var encodedParam = "";
  1509.     if (charset)
  1510.       encodedParam = escape(convertFromUnicode(charset, param));
  1511.     else // Default charset is UTF-8
  1512.       encodedParam = encodeURIComponent(param);
  1513.  
  1514.     shortcutURL = shortcutURL.replace(/%s/g, encodedParam).replace(/%S/g, param);
  1515.  
  1516.     if (/%s/i.test(postData)) // POST keyword
  1517.       aPostDataRef.value = getPostDataStream(postData, param, encodedParam,
  1518.                                              "application/x-www-form-urlencoded");
  1519.   }
  1520.   else if (param) {
  1521.     // This keyword doesn't take a parameter, but one was provided. Just return
  1522.     // the original URL.
  1523.     aPostDataRef.value = null;
  1524.  
  1525.     return aURL;
  1526.   }
  1527.  
  1528.   return shortcutURL;
  1529. }
  1530.  
  1531. function getPostDataStream(aStringData, aKeyword, aEncKeyword, aType) {
  1532.   var dataStream = Cc["@mozilla.org/io/string-input-stream;1"].
  1533.                    createInstance(Ci.nsIStringInputStream);
  1534.   aStringData = aStringData.replace(/%s/g, aEncKeyword).replace(/%S/g, aKeyword);
  1535.   dataStream.data = aStringData;
  1536.  
  1537.   var mimeStream = Cc["@mozilla.org/network/mime-input-stream;1"].
  1538.                    createInstance(Ci.nsIMIMEInputStream);
  1539.   mimeStream.addHeader("Content-Type", aType);
  1540.   mimeStream.addContentLength = true;
  1541.   mimeStream.setData(dataStream);
  1542.   return mimeStream.QueryInterface(Ci.nsIInputStream);
  1543. }
  1544.  
  1545. function readFromClipboard()
  1546. {
  1547.   var url;
  1548.  
  1549.   try {
  1550.     // Get clipboard.
  1551.     var clipboard = Components.classes["@mozilla.org/widget/clipboard;1"]
  1552.                               .getService(Components.interfaces.nsIClipboard);
  1553.  
  1554.     // Create tranferable that will transfer the text.
  1555.     var trans = Components.classes["@mozilla.org/widget/transferable;1"]
  1556.                           .createInstance(Components.interfaces.nsITransferable);
  1557.  
  1558.     trans.addDataFlavor("text/unicode");
  1559.  
  1560.     // If available, use selection clipboard, otherwise global one
  1561.     if (clipboard.supportsSelectionClipboard())
  1562.       clipboard.getData(trans, clipboard.kSelectionClipboard);
  1563.     else
  1564.       clipboard.getData(trans, clipboard.kGlobalClipboard);
  1565.  
  1566.     var data = {};
  1567.     var dataLen = {};
  1568.     trans.getTransferData("text/unicode", data, dataLen);
  1569.  
  1570.     if (data) {
  1571.       data = data.value.QueryInterface(Components.interfaces.nsISupportsString);
  1572.       url = data.data.substring(0, dataLen.value / 2);
  1573.     }
  1574.   } catch (ex) {
  1575.   }
  1576.  
  1577.   return url;
  1578. }
  1579.  
  1580. function BrowserViewSourceOfDocument(aDocument)
  1581. {
  1582.   var pageCookie;
  1583.   var webNav;
  1584.  
  1585.   // Get the document charset
  1586.   var docCharset = "charset=" + aDocument.characterSet;
  1587.  
  1588.   // Get the nsIWebNavigation associated with the document
  1589.   try {
  1590.       var win;
  1591.       var ifRequestor;
  1592.  
  1593.       // Get the DOMWindow for the requested document.  If the DOMWindow
  1594.       // cannot be found, then just use the content window...
  1595.       //
  1596.       // XXX:  This is a bit of a hack...
  1597.       win = aDocument.defaultView;
  1598.       if (win == window) {
  1599.         win = content;
  1600.       }
  1601.       ifRequestor = win.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
  1602.  
  1603.       webNav = ifRequestor.getInterface(nsIWebNavigation);
  1604.   } catch(err) {
  1605.       // If nsIWebNavigation cannot be found, just get the one for the whole
  1606.       // window...
  1607.       webNav = getWebNavigation();
  1608.   }
  1609.   //
  1610.   // Get the 'PageDescriptor' for the current document. This allows the
  1611.   // view-source to access the cached copy of the content rather than
  1612.   // refetching it from the network...
  1613.   //
  1614.   try{
  1615.     var PageLoader = webNav.QueryInterface(Components.interfaces.nsIWebPageDescriptor);
  1616.  
  1617.     pageCookie = PageLoader.currentDescriptor;
  1618.   } catch(err) {
  1619.     // If no page descriptor is available, just use the view-source URL...
  1620.   }
  1621.  
  1622.   ViewSourceOfURL(webNav.currentURI.spec, pageCookie, aDocument);
  1623. }
  1624.  
  1625. function ViewSourceOfURL(aURL, aPageDescriptor, aDocument)
  1626. {
  1627.   var utils = window.top.gViewSourceUtils;
  1628.   if (getBoolPref("view_source.editor.external", false)) {
  1629.     utils.openInExternalEditor(aURL, aPageDescriptor, aDocument);
  1630.   }
  1631.   else {
  1632.     utils.openInInternalViewer(aURL, aPageDescriptor, aDocument);
  1633.   }
  1634. }
  1635.  
  1636. // doc - document to use for source, or null for this window's document
  1637. // initialTab - name of the initial tab to display, or null for the first tab
  1638. function BrowserPageInfo(doc, initialTab)
  1639. {
  1640.   var args = {doc: doc, initialTab: initialTab};
  1641.   toOpenDialogByTypeAndUrl("Browser:page-info",
  1642.                            doc ? doc.location : window.content.document.location,
  1643.                            "chrome://browser/content/pageinfo/pageInfo.xul",
  1644.                            "chrome,toolbar,dialog=no,resizable",
  1645.                            args);
  1646. }
  1647.  
  1648. //@line 1952 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  1649.  
  1650. function checkForDirectoryListing()
  1651. {
  1652.   if ( "HTTPIndex" in content &&
  1653.        content.HTTPIndex instanceof Components.interfaces.nsIHTTPIndex ) {
  1654.     content.wrappedJSObject.defaultCharacterset =
  1655.       getMarkupDocumentViewer().defaultCharacterSet;
  1656.   }
  1657. }
  1658.  
  1659. function URLBarSetURI(aURI) {
  1660.   var value = getBrowser().userTypedValue;
  1661.   var state = "invalid";
  1662.  
  1663.   if (!value) {
  1664.     if (aURI) {
  1665.       // If the url has "wyciwyg://" as the protocol, strip it off.
  1666.       // Nobody wants to see it on the urlbar for dynamically generated
  1667.       // pages.
  1668.       if (!gURIFixup)
  1669.         gURIFixup = Cc["@mozilla.org/docshell/urifixup;1"]
  1670.                       .getService(Ci.nsIURIFixup);
  1671.       try {
  1672.         aURI = gURIFixup.createExposableURI(aURI);
  1673.       } catch (ex) {}
  1674.     } else {
  1675.       aURI = getWebNavigation().currentURI;
  1676.     }
  1677.  
  1678.     if (aURI.spec == "about:blank") {
  1679.       // Replace "about:blank" with an empty string
  1680.       // only if there's no opener (bug 370555).
  1681.       value = content.opener ? aURI.spec : "";
  1682.     } else {
  1683.       value = losslessDecodeURI(aURI);
  1684.       state = "valid";
  1685.     }
  1686.   }
  1687.  
  1688.   gURLBar.value = value;
  1689.   SetPageProxyState(state);
  1690. }
  1691.  
  1692. function losslessDecodeURI(aURI) {
  1693.   var value = aURI.spec;
  1694.   // Try to decode as UTF-8 if there's no encoding sequence that we would break.
  1695.   if (!/%25(?:3B|2F|3F|3A|40|26|3D|2B|24|2C|23)/i.test(value))
  1696.     try {
  1697.       value = decodeURI(value)
  1698.                 // 1. decodeURI decodes %25 to %, which creates unintended
  1699.                 //    encoding sequences. Re-encode it, unless it's part of
  1700.                 //    a sequence that survived decodeURI, i.e. one for:
  1701.                 //    ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '#'
  1702.                 //    (RFC 3987 section 3.2)
  1703.                 // 2. Re-encode whitespace so that it doesn't get eaten away
  1704.                 //    by the location bar (bug 410726).
  1705.                 .replace(/%(?!3B|2F|3F|3A|40|26|3D|2B|24|2C|23)|[\r\n\t]/ig,
  1706.                          encodeURIComponent);
  1707.     } catch (e) {}
  1708.  
  1709.   // Encode invisible characters (soft hyphen, zero-width space, BOM,
  1710.   // line and paragraph separator, word joiner, invisible times,
  1711.   // invisible separator, object replacement character) (bug 452979)
  1712.   value = value.replace(/[\v\x0c\x1c\x1d\x1e\x1f\u00ad\u200b\ufeff\u2028\u2029\u2060\u2062\u2063\ufffc]/g,
  1713.                         encodeURIComponent);
  1714.  
  1715.   // Encode bidirectional formatting characters.
  1716.   // (RFC 3987 sections 3.2 and 4.1 paragraph 6)
  1717.   value = value.replace(/[\u200e\u200f\u202a\u202b\u202c\u202d\u202e]/g,
  1718.                         encodeURIComponent);
  1719.   return value;
  1720. }
  1721.  
  1722. // Replace the urlbar's value with the url of the page.
  1723. function handleURLBarRevert() {
  1724.   var throbberElement = document.getElementById("navigator-throbber");
  1725.   var isScrolling = gURLBar.popupOpen;
  1726.  
  1727.   gBrowser.userTypedValue = null;
  1728.  
  1729.   // don't revert to last valid url unless page is NOT loading
  1730.   // and user is NOT key-scrolling through autocomplete list
  1731.   if ((!throbberElement || !throbberElement.hasAttribute("busy")) && !isScrolling) {
  1732.     URLBarSetURI();
  1733.  
  1734.     // If the value isn't empty and the urlbar has focus, select the value.
  1735.     if (gURLBar.value && gURLBar.hasAttribute("focused"))
  1736.       gURLBar.select();
  1737.   }
  1738.  
  1739.   // tell widget to revert to last typed text only if the user
  1740.   // was scrolling when they hit escape
  1741.   return !isScrolling;
  1742. }
  1743.  
  1744. function handleURLBarCommand(aTriggeringEvent) {
  1745.   if (!gURLBar.value)
  1746.     return;
  1747.  
  1748.   var postData = { };
  1749.   canonizeUrl(aTriggeringEvent, postData);
  1750.  
  1751.   try {
  1752.     addToUrlbarHistory(gURLBar.value);
  1753.   } catch (ex) {
  1754.     // Things may go wrong when adding url to session history,
  1755.     // but don't let that interfere with the loading of the url.
  1756.   }
  1757.  
  1758.   BrowserLoadURL(aTriggeringEvent, postData.value);
  1759. }
  1760.  
  1761. function canonizeUrl(aTriggeringEvent, aPostDataRef) {
  1762.   if (!gURLBar || !gURLBar.value)
  1763.     return;
  1764.  
  1765.   var url = gURLBar.value;
  1766.  
  1767.   // Only add the suffix when the URL bar value isn't already "URL-like".
  1768.   // Since this function is called from handleURLBarCommand, which receives
  1769.   // both mouse (from the go button) and keyboard events, we also make sure not
  1770.   // to do the fixup unless we get a keyboard event, to match user expectations.
  1771.   if (!/^(www|https?)\b|\/\s*$/i.test(url) &&
  1772.       (aTriggeringEvent instanceof KeyEvent)) {
  1773. //@line 2079 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  1774.     var accel = aTriggeringEvent.ctrlKey;
  1775. //@line 2081 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  1776.     var shift = aTriggeringEvent.shiftKey;
  1777.  
  1778.     var suffix = "";
  1779.  
  1780.     switch (true) {
  1781.       case (accel && shift):
  1782.         suffix = ".org/";
  1783.         break;
  1784.       case (shift):
  1785.         suffix = ".net/";
  1786.         break;
  1787.       case (accel):
  1788.         try {
  1789.           suffix = gPrefService.getCharPref("browser.fixup.alternate.suffix");
  1790.           if (suffix.charAt(suffix.length - 1) != "/")
  1791.             suffix += "/";
  1792.         } catch(e) {
  1793.           suffix = ".com/";
  1794.         }
  1795.         break;
  1796.     }
  1797.  
  1798.     if (suffix) {
  1799.       // trim leading/trailing spaces (bug 233205)
  1800.       url = url.replace(/^\s+/, "").replace(/\s+$/, "");
  1801.  
  1802.       // Tack www. and suffix on.  If user has appended directories, insert
  1803.       // suffix before them (bug 279035).  Be careful not to get two slashes.
  1804.       // Also, don't add the suffix if it's in the original url (bug 233853).
  1805.       
  1806.       var firstSlash = url.indexOf("/");
  1807.       var existingSuffix = url.indexOf(suffix.substring(0, suffix.length - 1));
  1808.  
  1809.       // * Logic for slash and existing suffix (example)
  1810.       // No slash, no suffix: Add suffix (mozilla)
  1811.       // No slash, yes suffix: Add slash (mozilla.com)
  1812.       // Yes slash, no suffix: Insert suffix (mozilla/stuff)
  1813.       // Yes slash, suffix before slash: Do nothing (mozilla.com/stuff)
  1814.       // Yes slash, suffix after slash: Insert suffix (mozilla/?stuff=.com)
  1815.       
  1816.       if (firstSlash >= 0) {
  1817.         if (existingSuffix == -1 || existingSuffix > firstSlash)
  1818.           url = url.substring(0, firstSlash) + suffix +
  1819.                 url.substring(firstSlash + 1);
  1820.       } else
  1821.         url = url + (existingSuffix == -1 ? suffix : "/");
  1822.  
  1823.       url = "http://www." + url;
  1824.     }
  1825.   }
  1826.  
  1827.   gURLBar.value = getShortcutOrURI(url, aPostDataRef);
  1828.  
  1829.   // Also update this so the browser display keeps the new value (bug 310651)
  1830.   gBrowser.userTypedValue = gURLBar.value;
  1831. }
  1832.  
  1833. function UpdateUrlbarSearchSplitterState()
  1834. {
  1835.   var splitter = document.getElementById("urlbar-search-splitter");
  1836.   var urlbar = document.getElementById("urlbar-container");
  1837.   var searchbar = document.getElementById("search-container");
  1838.  
  1839.   var ibefore = null;
  1840.   if (urlbar && searchbar) {
  1841.     if (urlbar.nextSibling == searchbar)
  1842.       ibefore = searchbar;
  1843.     else if (searchbar.nextSibling == urlbar)
  1844.       ibefore = urlbar;
  1845.   }
  1846.  
  1847.   if (ibefore) {
  1848.     if (!splitter) {
  1849.       splitter = document.createElement("splitter");
  1850.       splitter.id = "urlbar-search-splitter";
  1851.       splitter.setAttribute("resizebefore", "flex");
  1852.       splitter.setAttribute("resizeafter", "flex");
  1853.       splitter.className = "chromeclass-toolbar-additional";
  1854.     }
  1855.     urlbar.parentNode.insertBefore(splitter, ibefore);
  1856.   } else if (splitter)
  1857.     splitter.parentNode.removeChild(splitter);
  1858. }
  1859.  
  1860. var LocationBarHelpers = {
  1861.   _timeoutID: null,
  1862.  
  1863.   _searchBegin: function LocBar_searchBegin() {
  1864.     function delayedBegin(self) {
  1865.       self._timeoutID = null;
  1866.       document.getElementById("urlbar-throbber").setAttribute("busy", "true");
  1867.     }
  1868.  
  1869.     this._timeoutID = setTimeout(delayedBegin, 500, this);
  1870.   },
  1871.  
  1872.   _searchComplete: function LocBar_searchComplete() {
  1873.     // Did we finish the search before delayedBegin was invoked?
  1874.     if (this._timeoutID) {
  1875.       clearTimeout(this._timeoutID);
  1876.       this._timeoutID = null;
  1877.     }
  1878.     document.getElementById("urlbar-throbber").removeAttribute("busy");
  1879.   }
  1880. };
  1881.  
  1882. function UpdatePageProxyState()
  1883. {
  1884.   if (gURLBar && gURLBar.value != gLastValidURLStr)
  1885.     SetPageProxyState("invalid");
  1886. }
  1887.  
  1888. function SetPageProxyState(aState)
  1889. {
  1890.   if (!gURLBar)
  1891.     return;
  1892.  
  1893.   if (!gProxyFavIcon)
  1894.     gProxyFavIcon = document.getElementById("page-proxy-favicon");
  1895.  
  1896.   gURLBar.setAttribute("pageproxystate", aState);
  1897.   gProxyFavIcon.setAttribute("pageproxystate", aState);
  1898.  
  1899.   // the page proxy state is set to valid via OnLocationChange, which
  1900.   // gets called when we switch tabs.
  1901.   if (aState == "valid") {
  1902.     gLastValidURLStr = gURLBar.value;
  1903.     gURLBar.addEventListener("input", UpdatePageProxyState, false);
  1904.  
  1905.     PageProxySetIcon(gBrowser.mCurrentBrowser.mIconURL);
  1906.   } else if (aState == "invalid") {
  1907.     gURLBar.removeEventListener("input", UpdatePageProxyState, false);
  1908.     PageProxyClearIcon();
  1909.   }
  1910. }
  1911.  
  1912. function PageProxySetIcon (aURL)
  1913. {
  1914.   if (!gProxyFavIcon)
  1915.     return;
  1916.  
  1917.   if (!aURL)
  1918.     PageProxyClearIcon();
  1919.   else if (gProxyFavIcon.getAttribute("src") != aURL)
  1920.     gProxyFavIcon.setAttribute("src", aURL);
  1921. }
  1922.  
  1923. function PageProxyClearIcon ()
  1924. {
  1925.   gProxyFavIcon.removeAttribute("src");
  1926. }
  1927.  
  1928.  
  1929. function PageProxyDragGesture(aEvent)
  1930. {
  1931.   if (gProxyFavIcon.getAttribute("pageproxystate") == "valid") {
  1932.     nsDragAndDrop.startDrag(aEvent, proxyIconDNDObserver);
  1933.     return true;
  1934.   }
  1935.   return false;
  1936. }
  1937.  
  1938. function PageProxyClickHandler(aEvent)
  1939. {
  1940.   if (aEvent.button == 1 && gPrefService.getBoolPref("middlemouse.paste"))
  1941.     middleMousePaste(aEvent);
  1942. }
  1943.  
  1944. function URLBarOnInput(evt)
  1945. {
  1946.   gBrowser.userTypedValue = gURLBar.value;
  1947.   
  1948.   // If the user is interacting with the url bar, get rid of the identity popup
  1949.   var ih = getIdentityHandler();
  1950.   if(ih._identityPopup)
  1951.     ih._identityPopup.hidePopup();
  1952. }
  1953.  
  1954. function BrowserImport()
  1955. {
  1956. //@line 2272 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  1957.   window.openDialog("chrome://browser/content/migration/migration.xul",
  1958.                     "migration", "modal,centerscreen,chrome,resizable=no");
  1959. //@line 2275 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  1960. }
  1961.  
  1962. /**
  1963.  * Handle command events bubbling up from error page content
  1964.  */
  1965. function BrowserOnCommand(event) {
  1966.     // Don't trust synthetic events
  1967.     if (!event.isTrusted)
  1968.       return;
  1969.  
  1970.     var ot = event.originalTarget;
  1971.     var errorDoc = ot.ownerDocument;
  1972.  
  1973.     // If the event came from an ssl error page, it is probably either the "Add
  1974.     // Exception…" or "Get me out of here!" button
  1975.     if (/^about:neterror\?e=nssBadCert/.test(errorDoc.documentURI)) {
  1976.       if (ot == errorDoc.getElementById('exceptionDialogButton')) {
  1977.         var params = { exceptionAdded : false };
  1978.         
  1979.         try {
  1980.           switch (gPrefService.getIntPref("browser.ssl_override_behavior")) {
  1981.             case 2 : // Pre-fetch & pre-populate
  1982.               params.prefetchCert = true;
  1983.             case 1 : // Pre-populate
  1984.               params.location = errorDoc.location.href;
  1985.           }
  1986.         } catch (e) {
  1987.           Components.utils.reportError("Couldn't get ssl_override pref: " + e);
  1988.         }
  1989.         
  1990.         window.openDialog('chrome://pippki/content/exceptionDialog.xul',
  1991.                           '','chrome,centerscreen,modal', params);
  1992.         
  1993.         // If the user added the exception cert, attempt to reload the page
  1994.         if (params.exceptionAdded)
  1995.           errorDoc.location.reload();
  1996.       }
  1997.       else if (ot == errorDoc.getElementById('getMeOutOfHereButton')) {
  1998.         getMeOutOfHere();
  1999.       }
  2000.     }
  2001.     else if (/^about:blocked/.test(errorDoc.documentURI)) {
  2002.       // The event came from a button on a malware/phishing block page
  2003.       
  2004.       if (ot == errorDoc.getElementById('getMeOutButton')) {
  2005.         getMeOutOfHere();
  2006.       }
  2007.       else if (ot == errorDoc.getElementById('reportButton')) {
  2008.         // This is the "Why is this site blocked" button.  For malware,
  2009.         // we can fetch a site-specific report, for phishing, we redirect
  2010.         // to the generic page describing phishing protection.
  2011.         var formatter = Cc["@mozilla.org/toolkit/URLFormatterService;1"]
  2012.                        .getService(Components.interfaces.nsIURLFormatter);
  2013.         
  2014.         if (/e=malwareBlocked/.test(errorDoc.documentURI)) {
  2015.           // Get the stop badware "why is this blocked" report url,
  2016.           // append the current url, and go there.
  2017.           try {
  2018.             var reportURL = formatter.formatURLPref("browser.safebrowsing.malware.reportURL");
  2019.             reportURL += errorDoc.location.href;
  2020.             content.location = reportURL;
  2021.           } catch (e) {
  2022.             Components.utils.reportError("Couldn't get malware report URL: " + e);
  2023.           }
  2024.         }
  2025.         else if (/e=phishingBlocked/.test(errorDoc.documentURI)) {
  2026.           try {
  2027.             content.location = formatter.formatURLPref("browser.safebrowsing.warning.infoURL");
  2028.           } catch (e) {
  2029.             Components.utils.reportError("Couldn't get phishing info URL: " + e);
  2030.           }
  2031.         }
  2032.       }
  2033.       else if (ot == errorDoc.getElementById('ignoreWarningButton')) {
  2034.         // Allow users to override and continue through to the site,
  2035.         // but add a notify bar as a reminder, so that they don't lose
  2036.         // track after, e.g., tab switching.
  2037.         gBrowser.loadURIWithFlags(content.location.href,
  2038.                                   nsIWebNavigation.LOAD_FLAGS_BYPASS_CLASSIFIER,
  2039.                                   null, null, null);
  2040.         var notificationBox = gBrowser.getNotificationBox();
  2041.         notificationBox.appendNotification(
  2042.           errorDoc.title, /* Re-use the error page's title, e.g. "Reported Web Forgery!" */
  2043.           "blocked-badware-page",
  2044.           "chrome://global/skin/icons/blacklist_favicon.png",
  2045.           notificationBox.PRIORITY_CRITICAL_HIGH,
  2046.           null
  2047.         );
  2048.       }
  2049.     }
  2050. }
  2051.  
  2052. /**
  2053.  * Re-direct the browser to a known-safe page.  This function is
  2054.  * used when, for example, the user browses to a known malware page
  2055.  * and is presented with about:blocked.  The "Get me out of here!"
  2056.  * button should take the user to the default start page so that even
  2057.  * when their own homepage is infected, we can get them somewhere safe.
  2058.  */
  2059. function getMeOutOfHere() {
  2060.   // Get the start page from the *default* pref branch, not the user's
  2061.   var prefs = Cc["@mozilla.org/preferences-service;1"]
  2062.              .getService(Ci.nsIPrefService).getDefaultBranch(null);
  2063.   var url = "about:blank";
  2064.   try {
  2065.     url = prefs.getComplexValue("browser.startup.homepage",
  2066.                                 Ci.nsIPrefLocalizedString).data;
  2067.     // If url is a pipe-delimited set of pages, just take the first one.
  2068.     if (url.indexOf("|") != -1)
  2069.       url = url.split("|")[0];
  2070.   } catch(e) {
  2071.     Components.utils.reportError("Couldn't get homepage pref: " + e);
  2072.   }
  2073.   content.location = url;
  2074. }
  2075.  
  2076. function BrowserFullScreen()
  2077. {
  2078.   window.fullScreen = !window.fullScreen;
  2079. }
  2080.  
  2081. function onFullScreen()
  2082. {
  2083.   FullScreen.toggle();
  2084. }
  2085.  
  2086. function getWebNavigation()
  2087. {
  2088.   try {
  2089.     return gBrowser.webNavigation;
  2090.   } catch (e) {
  2091.     return null;
  2092.   }
  2093. }
  2094.  
  2095. function BrowserReloadWithFlags(reloadFlags)
  2096. {
  2097.   /* First, we'll try to use the session history object to reload so
  2098.    * that framesets are handled properly. If we're in a special
  2099.    * window (such as view-source) that has no session history, fall
  2100.    * back on using the web navigation's reload method.
  2101.    */
  2102.  
  2103.   var webNav = getWebNavigation();
  2104.   try {
  2105.     var sh = webNav.sessionHistory;
  2106.     if (sh)
  2107.       webNav = sh.QueryInterface(nsIWebNavigation);
  2108.   } catch (e) {
  2109.   }
  2110.  
  2111.   try {
  2112.     webNav.reload(reloadFlags);
  2113.   } catch (e) {
  2114.   }
  2115. }
  2116.  
  2117. function toggleAffectedChrome(aHide)
  2118. {
  2119.   // chrome to toggle includes:
  2120.   //   (*) menubar
  2121.   //   (*) navigation bar
  2122.   //   (*) bookmarks toolbar
  2123.   //   (*) tabstrip
  2124.   //   (*) browser messages
  2125.   //   (*) sidebar
  2126.   //   (*) find bar
  2127.   //   (*) statusbar
  2128.  
  2129.   getNavToolbox().hidden = aHide;
  2130.   if (aHide)
  2131.   {
  2132.     gChromeState = {};
  2133.     var sidebar = document.getElementById("sidebar-box");
  2134.     gChromeState.sidebarOpen = !sidebar.hidden;
  2135.     gSidebarCommand = sidebar.getAttribute("sidebarcommand");
  2136.  
  2137.     gChromeState.hadTabStrip = gBrowser.getStripVisibility();
  2138.     gBrowser.setStripVisibilityTo(false);
  2139.  
  2140.     var notificationBox = gBrowser.getNotificationBox();
  2141.     gChromeState.notificationsOpen = !notificationBox.notificationsHidden;
  2142.     notificationBox.notificationsHidden = aHide;
  2143.  
  2144.     document.getElementById("sidebar").setAttribute("src", "about:blank");
  2145.     var statusbar = document.getElementById("status-bar");
  2146.     gChromeState.statusbarOpen = !statusbar.hidden;
  2147.     statusbar.hidden = aHide;
  2148.  
  2149.     gChromeState.findOpen = !gFindBar.hidden;
  2150.     gFindBar.close();
  2151.   }
  2152.   else {
  2153.     if (gChromeState.hadTabStrip) {
  2154.       gBrowser.setStripVisibilityTo(true);
  2155.     }
  2156.  
  2157.     if (gChromeState.notificationsOpen) {
  2158.       gBrowser.getNotificationBox().notificationsHidden = aHide;
  2159.     }
  2160.  
  2161.     if (gChromeState.statusbarOpen) {
  2162.       var statusbar = document.getElementById("status-bar");
  2163.       statusbar.hidden = aHide;
  2164.     }
  2165.  
  2166.     if (gChromeState.findOpen)
  2167.       gFindBar.open();
  2168.   }
  2169.  
  2170.   if (gChromeState.sidebarOpen)
  2171.     toggleSidebar(gSidebarCommand);
  2172. }
  2173.  
  2174. function onEnterPrintPreview()
  2175. {
  2176.   gInPrintPreviewMode = true;
  2177.   toggleAffectedChrome(true);
  2178. }
  2179.  
  2180. function onExitPrintPreview()
  2181. {
  2182.   // restore chrome to original state
  2183.   gInPrintPreviewMode = false;
  2184.   FullZoom.setSettingValue();
  2185.   toggleAffectedChrome(false);
  2186. }
  2187.  
  2188. function getPPBrowser()
  2189. {
  2190.   return getBrowser();
  2191. }
  2192.  
  2193. function getMarkupDocumentViewer()
  2194. {
  2195.   return gBrowser.markupDocumentViewer;
  2196. }
  2197.  
  2198. /**
  2199.  * Content area tooltip.
  2200.  * XXX - this must move into XBL binding/equiv! Do not want to pollute
  2201.  *       browser.js with functionality that can be encapsulated into
  2202.  *       browser widget. TEMPORARY!
  2203.  *
  2204.  * NOTE: Any changes to this routine need to be mirrored in ChromeListener::FindTitleText()
  2205.  *       (located in mozilla/embedding/browser/webBrowser/nsDocShellTreeOwner.cpp)
  2206.  *       which performs the same function, but for embedded clients that
  2207.  *       don't use a XUL/JS layer. It is important that the logic of
  2208.  *       these two routines be kept more or less in sync.
  2209.  *       (pinkerton)
  2210.  **/
  2211. function FillInHTMLTooltip(tipElement)
  2212. {
  2213.   var retVal = false;
  2214.   if (tipElement.namespaceURI == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul")
  2215.     return retVal;
  2216.  
  2217.   const XLinkNS = "http://www.w3.org/1999/xlink";
  2218.  
  2219.  
  2220.   var titleText = null;
  2221.   var XLinkTitleText = null;
  2222.   var direction = tipElement.ownerDocument.dir;
  2223.  
  2224.   while (!titleText && !XLinkTitleText && tipElement) {
  2225.     if (tipElement.nodeType == Node.ELEMENT_NODE) {
  2226.       titleText = tipElement.getAttribute("title");
  2227.       XLinkTitleText = tipElement.getAttributeNS(XLinkNS, "title");
  2228.       var defView = tipElement.ownerDocument.defaultView;
  2229.       // XXX Work around bug 350679:
  2230.       // "Tooltips can be fired in documents with no view".
  2231.       if (!defView)
  2232.         return retVal;
  2233.       direction = defView.getComputedStyle(tipElement, "")
  2234.         .getPropertyValue("direction");
  2235.     }
  2236.     tipElement = tipElement.parentNode;
  2237.   }
  2238.  
  2239.   var tipNode = document.getElementById("aHTMLTooltip");
  2240.   tipNode.style.direction = direction;
  2241.   
  2242.   for each (var t in [titleText, XLinkTitleText]) {
  2243.     if (t && /\S/.test(t)) {
  2244.  
  2245.       // Per HTML 4.01 6.2 (CDATA section), literal CRs and tabs should be
  2246.       // replaced with spaces, and LFs should be removed entirely.
  2247.       // XXX Bug 322270: We don't preserve the result of entities like  ,
  2248.       // which should result in a line break in the tooltip, because we can't
  2249.       // distinguish that from a literal character in the source by this point.
  2250.       t = t.replace(/[\r\t]/g, ' ');
  2251.       t = t.replace(/\n/g, '');
  2252.  
  2253.       tipNode.setAttribute("label", t);
  2254.       retVal = true;
  2255.     }
  2256.   }
  2257.  
  2258.   return retVal;
  2259. }
  2260.  
  2261. var proxyIconDNDObserver = {
  2262.   onDragStart: function (aEvent, aXferData, aDragAction)
  2263.     {
  2264.       var value = content.location.href;
  2265.       var urlString = value + "\n" + content.document.title;
  2266.       var htmlString = "<a href=\"" + value + "\">" + value + "</a>";
  2267.  
  2268.       aXferData.data = new TransferData();
  2269.       aXferData.data.addDataForFlavour("text/x-moz-url", urlString);
  2270.       aXferData.data.addDataForFlavour("text/unicode", value);
  2271.       aXferData.data.addDataForFlavour("text/html", htmlString);
  2272.  
  2273.       // we're copying the URL from the proxy icon, not moving
  2274.       // we specify all of them though, because d&d sucks and OS's
  2275.       // get confused if they don't get the one they want
  2276.       aDragAction.action =
  2277.         Components.interfaces.nsIDragService.DRAGDROP_ACTION_COPY |
  2278.         Components.interfaces.nsIDragService.DRAGDROP_ACTION_MOVE |
  2279.         Components.interfaces.nsIDragService.DRAGDROP_ACTION_LINK;
  2280.     }
  2281. }
  2282.  
  2283. var homeButtonObserver = {
  2284.   onDrop: function (aEvent, aXferData, aDragSession)
  2285.     {
  2286.       var url = transferUtils.retrieveURLFromData(aXferData.data, aXferData.flavour.contentType);
  2287.       setTimeout(openHomeDialog, 0, url);
  2288.     },
  2289.  
  2290.   onDragOver: function (aEvent, aFlavour, aDragSession)
  2291.     {
  2292.       var statusTextFld = document.getElementById("statusbar-display");
  2293.       statusTextFld.label = gNavigatorBundle.getString("droponhomebutton");
  2294.       aDragSession.dragAction = Components.interfaces.nsIDragService.DRAGDROP_ACTION_LINK;
  2295.     },
  2296.  
  2297.   onDragExit: function (aEvent, aDragSession)
  2298.     {
  2299.       var statusTextFld = document.getElementById("statusbar-display");
  2300.       statusTextFld.label = "";
  2301.     },
  2302.  
  2303.   getSupportedFlavours: function ()
  2304.     {
  2305.       var flavourSet = new FlavourSet();
  2306.       flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  2307.       flavourSet.appendFlavour("text/x-moz-url");
  2308.       flavourSet.appendFlavour("text/unicode");
  2309.       return flavourSet;
  2310.     }
  2311. }
  2312.  
  2313. function openHomeDialog(aURL)
  2314. {
  2315.   var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
  2316.   var promptTitle = gNavigatorBundle.getString("droponhometitle");
  2317.   var promptMsg   = gNavigatorBundle.getString("droponhomemsg");
  2318.   var pressedVal  = promptService.confirmEx(window, promptTitle, promptMsg,
  2319.                           promptService.STD_YES_NO_BUTTONS,
  2320.                           null, null, null, null, {value:0});
  2321.  
  2322.   if (pressedVal == 0) {
  2323.     try {
  2324.       var str = Components.classes["@mozilla.org/supports-string;1"]
  2325.                           .createInstance(Components.interfaces.nsISupportsString);
  2326.       str.data = aURL;
  2327.       gPrefService.setComplexValue("browser.startup.homepage",
  2328.                                    Components.interfaces.nsISupportsString, str);
  2329.       var homeButton = document.getElementById("home-button");
  2330.       homeButton.setAttribute("tooltiptext", aURL);
  2331.     } catch (ex) {
  2332.       dump("Failed to set the home page.\n"+ex+"\n");
  2333.     }
  2334.   }
  2335. }
  2336.  
  2337. var bookmarksButtonObserver = {
  2338.   onDrop: function (aEvent, aXferData, aDragSession)
  2339.   {
  2340.     var split = aXferData.data.split("\n");
  2341.     var url = split[0];
  2342.     if (url != aXferData.data)  // do nothing if it's not a valid URL
  2343.       PlacesUIUtils.showMinimalAddBookmarkUI(makeURI(url), split[1]);
  2344.   },
  2345.  
  2346.   onDragOver: function (aEvent, aFlavour, aDragSession)
  2347.   {
  2348.     var statusTextFld = document.getElementById("statusbar-display");
  2349.     statusTextFld.label = gNavigatorBundle.getString("droponbookmarksbutton");
  2350.     aDragSession.dragAction = Components.interfaces.nsIDragService.DRAGDROP_ACTION_LINK;
  2351.   },
  2352.  
  2353.   onDragExit: function (aEvent, aDragSession)
  2354.   {
  2355.     var statusTextFld = document.getElementById("statusbar-display");
  2356.     statusTextFld.label = "";
  2357.   },
  2358.  
  2359.   getSupportedFlavours: function ()
  2360.   {
  2361.     var flavourSet = new FlavourSet();
  2362.     flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  2363.     flavourSet.appendFlavour("text/x-moz-url");
  2364.     flavourSet.appendFlavour("text/unicode");
  2365.     return flavourSet;
  2366.   }
  2367. }
  2368.  
  2369. var newTabButtonObserver = {
  2370.   onDragOver: function(aEvent, aFlavour, aDragSession)
  2371.     {
  2372.       var statusTextFld = document.getElementById("statusbar-display");
  2373.       statusTextFld.label = gNavigatorBundle.getString("droponnewtabbutton");
  2374.       aEvent.target.setAttribute("dragover", "true");
  2375.       return true;
  2376.     },
  2377.   onDragExit: function (aEvent, aDragSession)
  2378.     {
  2379.       var statusTextFld = document.getElementById("statusbar-display");
  2380.       statusTextFld.label = "";
  2381.       aEvent.target.removeAttribute("dragover");
  2382.     },
  2383.   onDrop: function (aEvent, aXferData, aDragSession)
  2384.     {
  2385.       var xferData = aXferData.data.split("\n");
  2386.       var draggedText = xferData[0] || xferData[1];
  2387.       var postData = {};
  2388.       var url = getShortcutOrURI(draggedText, postData);
  2389.       if (url) {
  2390.         nsDragAndDrop.dragDropSecurityCheck(aEvent, aDragSession, url);
  2391.         // allow third-party services to fixup this URL
  2392.         openNewTabWith(url, null, postData.value, aEvent, true);
  2393.       }
  2394.     },
  2395.   getSupportedFlavours: function ()
  2396.     {
  2397.       var flavourSet = new FlavourSet();
  2398.       flavourSet.appendFlavour("text/unicode");
  2399.       flavourSet.appendFlavour("text/x-moz-url");
  2400.       flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  2401.       return flavourSet;
  2402.     }
  2403. }
  2404.  
  2405. var newWindowButtonObserver = {
  2406.   onDragOver: function(aEvent, aFlavour, aDragSession)
  2407.     {
  2408.       var statusTextFld = document.getElementById("statusbar-display");
  2409.       statusTextFld.label = gNavigatorBundle.getString("droponnewwindowbutton");
  2410.       aEvent.target.setAttribute("dragover", "true");
  2411.       return true;
  2412.     },
  2413.   onDragExit: function (aEvent, aDragSession)
  2414.     {
  2415.       var statusTextFld = document.getElementById("statusbar-display");
  2416.       statusTextFld.label = "";
  2417.       aEvent.target.removeAttribute("dragover");
  2418.     },
  2419.   onDrop: function (aEvent, aXferData, aDragSession)
  2420.     {
  2421.       var xferData = aXferData.data.split("\n");
  2422.       var draggedText = xferData[0] || xferData[1];
  2423.       var postData = {};
  2424.       var url = getShortcutOrURI(draggedText, postData);
  2425.       if (url) {
  2426.         nsDragAndDrop.dragDropSecurityCheck(aEvent, aDragSession, url);
  2427.         // allow third-party services to fixup this URL
  2428.         openNewWindowWith(url, null, postData.value, true);
  2429.       }
  2430.     },
  2431.   getSupportedFlavours: function ()
  2432.     {
  2433.       var flavourSet = new FlavourSet();
  2434.       flavourSet.appendFlavour("text/unicode");
  2435.       flavourSet.appendFlavour("text/x-moz-url");
  2436.       flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  2437.       return flavourSet;
  2438.     }
  2439. }
  2440.  
  2441. var DownloadsButtonDNDObserver = {
  2442.   /////////////////////////////////////////////////////////////////////////////
  2443.   // nsDragAndDrop
  2444.   onDragOver: function (aEvent, aFlavour, aDragSession)
  2445.   {
  2446.     var statusTextFld = document.getElementById("statusbar-display");
  2447.     statusTextFld.label = gNavigatorBundle.getString("dropondownloadsbutton");
  2448.     aDragSession.canDrop = (aFlavour.contentType == "text/x-moz-url" ||
  2449.                             aFlavour.contentType == "text/unicode");
  2450.   },
  2451.  
  2452.   onDragExit: function (aEvent, aDragSession)
  2453.   {
  2454.     var statusTextFld = document.getElementById("statusbar-display");
  2455.     statusTextFld.label = "";
  2456.   },
  2457.  
  2458.   onDrop: function (aEvent, aXferData, aDragSession)
  2459.   {
  2460.     var split = aXferData.data.split("\n");
  2461.     var url = split[0];
  2462.     if (url != aXferData.data) {  //do nothing, not a valid URL
  2463.       nsDragAndDrop.dragDropSecurityCheck(aEvent, aDragSession, url);
  2464.  
  2465.       var name = split[1];
  2466.       saveURL(url, name, null, true, true);
  2467.     }
  2468.   },
  2469.   getSupportedFlavours: function ()
  2470.   {
  2471.     var flavourSet = new FlavourSet();
  2472.     flavourSet.appendFlavour("text/x-moz-url");
  2473.     flavourSet.appendFlavour("text/unicode");
  2474.     return flavourSet;
  2475.   }
  2476. }
  2477.  
  2478. const DOMLinkHandler = {
  2479.   handleEvent: function (event) {
  2480.     switch (event.type) {
  2481.       case "DOMLinkAdded":
  2482.         this.onLinkAdded(event);
  2483.         break;
  2484.     }
  2485.   },
  2486.   onLinkAdded: function (event) {
  2487.     var link = event.originalTarget;
  2488.     var rel = link.rel && link.rel.toLowerCase();
  2489.     if (!link || !link.ownerDocument || !rel || !link.href)
  2490.       return;
  2491.  
  2492.     var feedAdded = false;
  2493.     var iconAdded = false;
  2494.     var searchAdded = false;
  2495.     var relStrings = rel.split(/\s+/);
  2496.     var rels = {};
  2497.     for (let i = 0; i < relStrings.length; i++)
  2498.       rels[relStrings[i]] = true;
  2499.  
  2500.     for (let relVal in rels) {
  2501.       switch (relVal) {
  2502.         case "feed":
  2503.         case "alternate":
  2504.           if (!feedAdded) {
  2505.             if (!rels.feed && rels.alternate && rels.stylesheet)
  2506.               break;
  2507.  
  2508.             var feed = { title: link.title, href: link.href, type: link.type };
  2509.             if (isValidFeed(feed, link.ownerDocument.nodePrincipal, rels.feed)) {
  2510.               FeedHandler.addFeed(feed, link.ownerDocument);
  2511.               feedAdded = true;
  2512.             }
  2513.           }
  2514.           break;
  2515.         case "icon":
  2516.           if (!iconAdded) {
  2517.             if (!gPrefService.getBoolPref("browser.chrome.site_icons"))
  2518.               break;
  2519.  
  2520.             var targetDoc = link.ownerDocument;
  2521.             var ios = Cc["@mozilla.org/network/io-service;1"].
  2522.                       getService(Ci.nsIIOService);
  2523.             var uri = ios.newURI(link.href, targetDoc.characterSet, null);
  2524.  
  2525.             if (gBrowser.isFailedIcon(uri))
  2526.               break;
  2527.  
  2528.             // Verify that the load of this icon is legal.
  2529.             // error pages can load their favicon, to be on the safe side,
  2530.             // only allow chrome:// favicons
  2531.             const aboutNeterr = /^about:neterror\?/;
  2532.             const aboutBlocked = /^about:blocked\?/;
  2533.             if (!(aboutNeterr.test(targetDoc.documentURI) ||
  2534.                   aboutBlocked.test(targetDoc.documentURI)) ||
  2535.                 !uri.schemeIs("chrome")) {
  2536.               var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"].
  2537.                         getService(Ci.nsIScriptSecurityManager);
  2538.               try {
  2539.                 ssm.checkLoadURIWithPrincipal(targetDoc.nodePrincipal, uri,
  2540.                                               Ci.nsIScriptSecurityManager.DISALLOW_SCRIPT);
  2541.               } catch(e) {
  2542.                 break;
  2543.               }
  2544.             }
  2545.  
  2546.             try {
  2547.               var contentPolicy = Cc["@mozilla.org/layout/content-policy;1"].
  2548.                                   getService(Ci.nsIContentPolicy);
  2549.             } catch(e) {
  2550.               break; // Refuse to load if we can't do a security check.
  2551.             }
  2552.  
  2553.             // Security says okay, now ask content policy
  2554.             if (contentPolicy.shouldLoad(Ci.nsIContentPolicy.TYPE_IMAGE,
  2555.                                          uri, targetDoc.documentURIObject,
  2556.                                          link, link.type, null)
  2557.                                          != Ci.nsIContentPolicy.ACCEPT)
  2558.               break;
  2559.  
  2560.             var browserIndex = gBrowser.getBrowserIndexForDocument(targetDoc);
  2561.             // no browser? no favicon.
  2562.             if (browserIndex == -1)
  2563.               break;
  2564.  
  2565.             var tab = gBrowser.mTabContainer.childNodes[browserIndex];
  2566.             gBrowser.setIcon(tab, link.href);
  2567.             iconAdded = true;
  2568.           }
  2569.           break;
  2570.         case "search":
  2571.           if (!searchAdded) {
  2572.             var type = link.type && link.type.toLowerCase();
  2573.             type = type.replace(/^\s+|\s*(?:;.*)?$/g, "");
  2574.  
  2575.             if (type == "application/opensearchdescription+xml" && link.title &&
  2576.                 /^(?:https?|ftp):/i.test(link.href)) {
  2577.               var engine = { title: link.title, href: link.href };
  2578.               BrowserSearch.addEngine(engine, link.ownerDocument);
  2579.               searchAdded = true;
  2580.             }
  2581.           }
  2582.           break;
  2583.       }
  2584.     }
  2585.   }
  2586. }
  2587.  
  2588. const BrowserSearch = {
  2589.   addEngine: function(engine, targetDoc) {
  2590.     if (!this.searchBar)
  2591.       return;
  2592.  
  2593.     var browser = gBrowser.getBrowserForDocument(targetDoc);
  2594.  
  2595.     // Check to see whether we've already added an engine with this title
  2596.     if (browser.engines) {
  2597.       if (browser.engines.some(function (e) e.title == engine.title))
  2598.         return;
  2599.     }
  2600.  
  2601.     // Append the URI and an appropriate title to the browser data.
  2602.     var iconURL = null;
  2603.     if (gBrowser.shouldLoadFavIcon(browser.currentURI))
  2604.       iconURL = browser.currentURI.prePath + "/favicon.ico";
  2605.  
  2606.     var hidden = false;
  2607.     // If this engine (identified by title) is already in the list, add it
  2608.     // to the list of hidden engines rather than to the main list.
  2609.     // XXX This will need to be changed when engines are identified by URL;
  2610.     // see bug 335102.
  2611.     var searchService = Cc["@mozilla.org/browser/search-service;1"].
  2612.                         getService(Ci.nsIBrowserSearchService);
  2613.     if (searchService.getEngineByName(engine.title))
  2614.       hidden = true;
  2615.  
  2616.     var engines = (hidden ? browser.hiddenEngines : browser.engines) || [];
  2617.  
  2618.     engines.push({ uri: engine.href,
  2619.                    title: engine.title,
  2620.                    icon: iconURL });
  2621.  
  2622.     if (hidden)
  2623.       browser.hiddenEngines = engines;
  2624.     else {
  2625.       browser.engines = engines;
  2626.       if (browser == gBrowser.mCurrentBrowser)
  2627.         this.updateSearchButton();
  2628.     }
  2629.   },
  2630.  
  2631.   /**
  2632.    * Update the browser UI to show whether or not additional engines are 
  2633.    * available when a page is loaded or the user switches tabs to a page that 
  2634.    * has search engines.
  2635.    */
  2636.   updateSearchButton: function() {
  2637.     var searchBar = this.searchBar;
  2638.     
  2639.     // The search bar binding might not be applied even though the element is
  2640.     // in the document (e.g. when the navigation toolbar is hidden), so check
  2641.     // for .searchButton specifically.
  2642.     if (!searchBar || !searchBar.searchButton)
  2643.       return;
  2644.  
  2645.     var engines = gBrowser.mCurrentBrowser.engines;
  2646.     if (engines && engines.length > 0)
  2647.       searchBar.searchButton.setAttribute("addengines", "true");
  2648.     else
  2649.       searchBar.searchButton.removeAttribute("addengines");
  2650.   },
  2651.  
  2652.   /**
  2653.    * Gives focus to the search bar, if it is present on the toolbar, or loads
  2654.    * the default engine's search form otherwise. For Mac, opens a new window
  2655.    * or focuses an existing window, if necessary.
  2656.    */
  2657.   webSearch: function BrowserSearch_webSearch() {
  2658. //@line 2996 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  2659.     if (window.fullScreen)
  2660.       FullScreen.mouseoverToggle(true);
  2661.  
  2662.     var searchBar = this.searchBar;
  2663.     if (isElementVisible(searchBar)) {
  2664.       searchBar.select();
  2665.       searchBar.focus();
  2666.     } else {
  2667.       var ss = Cc["@mozilla.org/browser/search-service;1"].
  2668.                getService(Ci.nsIBrowserSearchService);
  2669.       var searchForm = ss.defaultEngine.searchForm;
  2670.       loadURI(searchForm, null, null, false);
  2671.     }
  2672.   },
  2673.  
  2674.   /**
  2675.    * Loads a search results page, given a set of search terms. Uses the current
  2676.    * engine if the search bar is visible, or the default engine otherwise.
  2677.    *
  2678.    * @param searchText
  2679.    *        The search terms to use for the search.
  2680.    *
  2681.    * @param useNewTab
  2682.    *        Boolean indicating whether or not the search should load in a new
  2683.    *        tab.
  2684.    */
  2685.   loadSearch: function BrowserSearch_search(searchText, useNewTab) {
  2686.     var ss = Cc["@mozilla.org/browser/search-service;1"].
  2687.              getService(Ci.nsIBrowserSearchService);
  2688.     var engine;
  2689.   
  2690.     // If the search bar is visible, use the current engine, otherwise, fall
  2691.     // back to the default engine.
  2692.     if (isElementVisible(this.searchBar))
  2693.       engine = ss.currentEngine;
  2694.     else
  2695.       engine = ss.defaultEngine;
  2696.   
  2697.     var submission = engine.getSubmission(searchText, null); // HTML response
  2698.  
  2699.     // getSubmission can return null if the engine doesn't have a URL
  2700.     // with a text/html response type.  This is unlikely (since
  2701.     // SearchService._addEngineToStore() should fail for such an engine),
  2702.     // but let's be on the safe side.
  2703.     if (!submission)
  2704.       return;
  2705.   
  2706.     if (useNewTab) {
  2707.       getBrowser().loadOneTab(submission.uri.spec, null, null,
  2708.                               submission.postData, null, false);
  2709.     } else
  2710.       loadURI(submission.uri.spec, null, submission.postData, false);
  2711.   },
  2712.  
  2713.   /**
  2714.    * Returns the search bar element if it is present in the toolbar, null otherwise.
  2715.    */
  2716.   get searchBar() {
  2717.     return document.getElementById("searchbar");
  2718.   },
  2719.  
  2720.   loadAddEngines: function BrowserSearch_loadAddEngines() {
  2721.     var newWindowPref = gPrefService.getIntPref("browser.link.open_newwindow");
  2722.     var where = newWindowPref == 3 ? "tab" : "window";
  2723.     var regionBundle = document.getElementById("bundle_browser_region");
  2724.     var searchEnginesURL = formatURL("browser.search.searchEnginesURL", true);
  2725.     openUILinkIn(searchEnginesURL, where);
  2726.   }
  2727. }
  2728.  
  2729. function FillHistoryMenu(aParent) {
  2730.   // Remove old entries if any
  2731.   var children = aParent.childNodes;
  2732.   for (var i = children.length - 1; i >= 0; --i) {
  2733.     if (children[i].hasAttribute("index"))
  2734.       aParent.removeChild(children[i]);
  2735.   }
  2736.  
  2737.   var webNav = getWebNavigation();
  2738.   var sessionHistory = webNav.sessionHistory;
  2739.   var bundle_browser = document.getElementById("bundle_browser");
  2740.  
  2741.   var count = sessionHistory.count;
  2742.   var index = sessionHistory.index;
  2743.   var end;
  2744.  
  2745.   if (count <= 1) // don't display the popup for a single item
  2746.     return false;
  2747.  
  2748.   var half_length = Math.floor(MAX_HISTORY_MENU_ITEMS / 2);
  2749.   var start = Math.max(index - half_length, 0);
  2750.   end = Math.min(start == 0 ? MAX_HISTORY_MENU_ITEMS : index + half_length + 1, count);
  2751.   if (end == count)
  2752.     start = Math.max(count - MAX_HISTORY_MENU_ITEMS, 0);
  2753.  
  2754.   var tooltipBack = bundle_browser.getString("tabHistory.goBack");
  2755.   var tooltipCurrent = bundle_browser.getString("tabHistory.current");
  2756.   var tooltipForward = bundle_browser.getString("tabHistory.goForward");
  2757.  
  2758.   for (var j = end - 1; j >= start; j--) {
  2759.     let item = document.createElement("menuitem");
  2760.     let entry = sessionHistory.getEntryAtIndex(j, false);
  2761.  
  2762.     item.setAttribute("label", entry.title || entry.URI.spec);
  2763.     item.setAttribute("index", j);
  2764.  
  2765.     if (j != index) {
  2766.       try {
  2767.         let iconURL = Cc["@mozilla.org/browser/favicon-service;1"]
  2768.                          .getService(Ci.nsIFaviconService)
  2769.                          .getFaviconForPage(entry.URI).spec;
  2770.         item.style.listStyleImage = "url(" + iconURL + ")";
  2771.       } catch (ex) {}
  2772.     }
  2773.  
  2774.     if (j < index) {
  2775.       item.className = "unified-nav-back menuitem-iconic";
  2776.       item.setAttribute("tooltiptext", tooltipBack);
  2777.     } else if (j == index) {
  2778.       item.setAttribute("type", "radio");
  2779.       item.setAttribute("checked", "true");
  2780.       item.className = "unified-nav-current";
  2781.       item.setAttribute("tooltiptext", tooltipCurrent);
  2782.     } else {
  2783.       item.className = "unified-nav-forward menuitem-iconic";
  2784.       item.setAttribute("tooltiptext", tooltipForward);
  2785.     }
  2786.  
  2787.     aParent.appendChild(item);
  2788.   }
  2789.   return true;
  2790. }
  2791.  
  2792. function addToUrlbarHistory(aUrlToAdd)
  2793. {
  2794.   if (!aUrlToAdd)
  2795.      return;
  2796.   if (aUrlToAdd.search(/[\x00-\x1F]/) != -1) // don't store bad URLs
  2797.      return;
  2798.  
  2799.    try {
  2800.      if (aUrlToAdd.indexOf(" ") == -1) {
  2801.        PlacesUIUtils.markPageAsTyped(aUrlToAdd);
  2802.      }
  2803.    }
  2804.    catch(ex) {
  2805.    }
  2806. }
  2807.  
  2808. function toJavaScriptConsole()
  2809. {
  2810.   toOpenWindowByType("global:console", "chrome://global/content/console.xul");
  2811. }
  2812.  
  2813. function BrowserDownloadsUI()
  2814. {
  2815.   Cc["@mozilla.org/download-manager-ui;1"].
  2816.   getService(Ci.nsIDownloadManagerUI).show(window);
  2817. }
  2818.  
  2819. function toOpenWindowByType(inType, uri, features)
  2820. {
  2821.   var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
  2822.   var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
  2823.   var topWindow = windowManagerInterface.getMostRecentWindow(inType);
  2824.  
  2825.   if (topWindow)
  2826.     topWindow.focus();
  2827.   else if (features)
  2828.     window.open(uri, "_blank", features);
  2829.   else
  2830.     window.open(uri, "_blank", "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar");
  2831. }
  2832.  
  2833. function toOpenDialogByTypeAndUrl(inType, relatedUrl, windowUri, features, extraArgument)
  2834. {
  2835.   var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService();
  2836.   var windowManagerInterface = windowManager.QueryInterface(Components.interfaces.nsIWindowMediator);
  2837.   var windows = windowManagerInterface.getEnumerator(inType);
  2838.  
  2839.   // Check for windows matching the url
  2840.   while (windows.hasMoreElements()) {
  2841.     var currentWindow = windows.getNext();
  2842.     if (currentWindow.document.documentElement.getAttribute("relatedUrl") == relatedUrl) {
  2843.         currentWindow.focus();
  2844.         return;
  2845.     }
  2846.   }
  2847.  
  2848.   // We didn't find a matching window, so open a new one.
  2849.   if (features)
  2850.     window.openDialog(windowUri, "_blank", features, extraArgument);
  2851.   else
  2852.     window.openDialog(windowUri, "_blank", "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar", extraArgument);
  2853. }
  2854.  
  2855. function OpenBrowserWindow()
  2856. {
  2857.   var charsetArg = new String();
  2858.   var handler = Components.classes["@mozilla.org/browser/clh;1"]
  2859.                           .getService(Components.interfaces.nsIBrowserHandler);
  2860.   var defaultArgs = handler.defaultArgs;
  2861.   var wintype = document.documentElement.getAttribute('windowtype');
  2862.  
  2863.   // if and only if the current window is a browser window and it has a document with a character
  2864.   // set, then extract the current charset menu setting from the current document and use it to
  2865.   // initialize the new browser window...
  2866.   var win;
  2867.   if (window && (wintype == "navigator:browser") && window.content && window.content.document)
  2868.   {
  2869.     var DocCharset = window.content.document.characterSet;
  2870.     charsetArg = "charset="+DocCharset;
  2871.  
  2872.     //we should "inherit" the charset menu setting in a new window
  2873.     win = window.openDialog("chrome://browser/content/", "_blank", "chrome,all,dialog=no", defaultArgs, charsetArg);
  2874.   }
  2875.   else // forget about the charset information.
  2876.   {
  2877.     win = window.openDialog("chrome://browser/content/", "_blank", "chrome,all,dialog=no", defaultArgs);
  2878.   }
  2879.  
  2880.   return win;
  2881. }
  2882.  
  2883. function BrowserCustomizeToolbar()
  2884. {
  2885.   // Disable the toolbar context menu items
  2886.   var menubar = document.getElementById("main-menubar");
  2887.   for (var i = 0; i < menubar.childNodes.length; ++i)
  2888.     menubar.childNodes[i].setAttribute("disabled", true);
  2889.  
  2890.   var cmd = document.getElementById("cmd_CustomizeToolbars");
  2891.   cmd.setAttribute("disabled", "true");
  2892.  
  2893.   var splitter = document.getElementById("urlbar-search-splitter");
  2894.   if (splitter)
  2895.     splitter.parentNode.removeChild(splitter);
  2896.  
  2897.   var customizeURL = "chrome://global/content/customizeToolbar.xul";
  2898. //@line 3253 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  2899.   window.openDialog(customizeURL,
  2900.                     "CustomizeToolbar",
  2901.                     "chrome,all,dependent",
  2902.                     getNavToolbox());
  2903. //@line 3258 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  2904. }
  2905.  
  2906. function BrowserToolboxCustomizeDone(aToolboxChanged)
  2907. {
  2908. //@line 3266 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  2909.  
  2910.   // Update global UI elements that may have been added or removed
  2911.   if (aToolboxChanged) {
  2912.     gURLBar = document.getElementById("urlbar");
  2913.     gProxyFavIcon = document.getElementById("page-proxy-favicon");
  2914.     gHomeButton.updateTooltip();
  2915.     gIdentityHandler._cacheElements();
  2916.     window.XULBrowserWindow.init();
  2917.  
  2918.     var backForwardDropmarker = document.getElementById("back-forward-dropmarker");
  2919.     if (backForwardDropmarker)
  2920.       backForwardDropmarker.disabled =
  2921.         document.getElementById('Browser:Back').hasAttribute('disabled') &&
  2922.         document.getElementById('Browser:Forward').hasAttribute('disabled');
  2923.  
  2924.     // support downgrading to Firefox 2.0
  2925.     var navBar = document.getElementById("nav-bar");
  2926.     navBar.setAttribute("currentset",
  2927.                         navBar.getAttribute("currentset")
  2928.                               .replace("unified-back-forward-button",
  2929.                                 "unified-back-forward-button,back-button,forward-button"));
  2930.     document.persist(navBar.id, "currentset");
  2931.  
  2932. //@line 3290 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  2933.     updateEditUIVisibility();
  2934. //@line 3292 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  2935.   }
  2936.  
  2937.   UpdateUrlbarSearchSplitterState();
  2938.  
  2939.   gHomeButton.updatePersonalToolbarStyle();
  2940.  
  2941.   // Update the urlbar
  2942.   if (gURLBar) {
  2943.     URLBarSetURI();
  2944.     XULBrowserWindow.asyncUpdateUI();
  2945.     PlacesStarButton.updateState();
  2946.   }
  2947.  
  2948.   // Re-enable parts of the UI we disabled during the dialog
  2949.   var menubar = document.getElementById("main-menubar");
  2950.   for (var i = 0; i < menubar.childNodes.length; ++i)
  2951.     menubar.childNodes[i].setAttribute("disabled", false);
  2952.   var cmd = document.getElementById("cmd_CustomizeToolbars");
  2953.   cmd.removeAttribute("disabled");
  2954.  
  2955.   // XXXmano bug 287105: wallpaper to bug 309953,
  2956.   // the reload button isn't in sync with the reload command.
  2957.   var reloadButton = document.getElementById("reload-button");
  2958.   if (reloadButton) {
  2959.     reloadButton.disabled =
  2960.       document.getElementById("Browser:Reload").getAttribute("disabled") == "true";
  2961.   }
  2962.  
  2963. //@line 3325 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  2964.  
  2965.   initBookmarksToolbar();
  2966.  
  2967. //@line 3329 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  2968.   // XXX Shouldn't have to do this, but I do
  2969.   window.focus();
  2970. //@line 3332 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  2971. }
  2972.  
  2973. function BrowserToolboxCustomizeChange() {
  2974.   gHomeButton.updatePersonalToolbarStyle();
  2975. }
  2976.  
  2977. /**
  2978.  * Update the global flag that tracks whether or not any edit UI (the Edit menu,
  2979.  * edit-related items in the context menu, and edit-related toolbar buttons
  2980.  * is visible, then update the edit commands' enabled state accordingly.  We use
  2981.  * this flag to skip updating the edit commands on focus or selection changes
  2982.  * when no UI is visible to improve performance (including pageload performance,
  2983.  * since focus changes when you load a new page).
  2984.  *
  2985.  * If UI is visible, we use goUpdateGlobalEditMenuItems to set the commands'
  2986.  * enabled state so the UI will reflect it appropriately.
  2987.  * 
  2988.  * If the UI isn't visible, we enable all edit commands so keyboard shortcuts
  2989.  * still work and just lazily disable them as needed when the user presses a
  2990.  * shortcut.
  2991.  *
  2992.  * This doesn't work on Mac, since Mac menus flash when users press their
  2993.  * keyboard shortcuts, so edit UI is essentially always visible on the Mac,
  2994.  * and we need to always update the edit commands.  Thus on Mac this function
  2995.  * is a no op.
  2996.  */
  2997. function updateEditUIVisibility()
  2998. {
  2999. //@line 3361 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  3000.   let editMenuPopupState = document.getElementById("menu_EditPopup").state;
  3001.   let contextMenuPopupState = document.getElementById("contentAreaContextMenu").state;
  3002.   let placesContextMenuPopupState = document.getElementById("placesContext").state;
  3003.  
  3004.   // The UI is visible if the Edit menu is opening or open, if the context menu
  3005.   // is open, or if the toolbar has been customized to include the Cut, Copy,
  3006.   // or Paste toolbar buttons.
  3007.   gEditUIVisible = editMenuPopupState == "showing" ||
  3008.                    editMenuPopupState == "open" ||
  3009.                    contextMenuPopupState == "showing" ||
  3010.                    contextMenuPopupState == "open" ||
  3011.                    placesContextMenuPopupState == "showing" ||
  3012.                    placesContextMenuPopupState == "open" ||
  3013.                    document.getElementById("cut-button") ||
  3014.                    document.getElementById("copy-button") ||
  3015.                    document.getElementById("paste-button") ? true : false;
  3016.  
  3017.   // If UI is visible, update the edit commands' enabled state to reflect
  3018.   // whether or not they are actually enabled for the current focus/selection.
  3019.   if (gEditUIVisible)
  3020.     goUpdateGlobalEditMenuItems();
  3021.  
  3022.   // Otherwise, enable all commands, so that keyboard shortcuts still work,
  3023.   // then lazily determine their actual enabled state when the user presses
  3024.   // a keyboard shortcut.
  3025.   else {
  3026.     goSetCommandEnabled("cmd_undo", true);
  3027.     goSetCommandEnabled("cmd_redo", true);
  3028.     goSetCommandEnabled("cmd_cut", true);
  3029.     goSetCommandEnabled("cmd_copy", true);
  3030.     goSetCommandEnabled("cmd_paste", true);
  3031.     goSetCommandEnabled("cmd_selectAll", true);
  3032.     goSetCommandEnabled("cmd_delete", true);
  3033.     goSetCommandEnabled("cmd_switchTextDirection", true);
  3034.   }
  3035. //@line 3397 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  3036. }
  3037.  
  3038. var FullScreen =
  3039. {
  3040.   _XULNS: "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul",
  3041.   toggle: function()
  3042.   {
  3043.     // show/hide all menubars, toolbars, and statusbars (except the full screen toolbar)
  3044.     this.showXULChrome("toolbar", window.fullScreen);
  3045.     this.showXULChrome("statusbar", window.fullScreen);
  3046.     document.getElementById("fullScreenItem").setAttribute("checked", !window.fullScreen);
  3047.  
  3048.     var fullScrToggler = document.getElementById("fullscr-toggler");
  3049.     if (!window.fullScreen) {
  3050.       // Add a tiny toolbar to receive mouseover and dragenter events, and provide affordance.
  3051.       // This will help simulate the "collapse" metaphor while also requiring less code and
  3052.       // events than raw listening of mouse coords.
  3053.       if (!fullScrToggler) {
  3054.         fullScrToggler = document.createElement("toolbar");
  3055.         fullScrToggler.id = "fullscr-toggler";
  3056.         fullScrToggler.setAttribute("customizable", "false");
  3057.         fullScrToggler.setAttribute("moz-collapsed", "true");
  3058.         var navBar = document.getElementById("nav-bar");
  3059.         navBar.parentNode.insertBefore(fullScrToggler, navBar);
  3060.       }
  3061.       fullScrToggler.addEventListener("mouseover", this._expandCallback, false);
  3062.       fullScrToggler.addEventListener("dragenter", this._expandCallback, false);
  3063.  
  3064.       if (gPrefService.getBoolPref("browser.fullscreen.autohide"))
  3065.         gBrowser.mPanelContainer.addEventListener("mousemove",
  3066.                                                   this._collapseCallback, false);
  3067.  
  3068.       document.addEventListener("keypress", this._keyToggleCallback, false);
  3069.       document.addEventListener("popupshown", this._setPopupOpen, false);
  3070.       document.addEventListener("popuphidden", this._setPopupOpen, false);
  3071.       this._shouldAnimate = true;
  3072.       this.mouseoverToggle(false);
  3073.  
  3074.       // Autohide prefs
  3075.       gPrefService.addObserver("browser.fullscreen", this, false);
  3076.     }
  3077.     else {
  3078.       document.removeEventListener("keypress", this._keyToggleCallback, false);
  3079.       document.removeEventListener("popupshown", this._setPopupOpen, false);
  3080.       document.removeEventListener("popuphidden", this._setPopupOpen, false);
  3081.       gPrefService.removeObserver("browser.fullscreen", this);
  3082.  
  3083.       if (fullScrToggler) {
  3084.         fullScrToggler.removeEventListener("mouseover", this._expandCallback, false);
  3085.         fullScrToggler.removeEventListener("dragenter", this._expandCallback, false);
  3086.       }
  3087.  
  3088.       // The user may quit fullscreen during an animation
  3089.       clearInterval(this._animationInterval);
  3090.       clearTimeout(this._animationTimeout);
  3091.       getNavToolbox().style.marginTop = "0px";
  3092.       if (this._isChromeCollapsed)
  3093.         this.mouseoverToggle(true);
  3094.       this._isAnimating = false;
  3095.       // This is needed if they use the context menu to quit fullscreen
  3096.       this._isPopupOpen = false;
  3097.  
  3098.       gBrowser.mPanelContainer.removeEventListener("mousemove",
  3099.                                                    this._collapseCallback, false);
  3100.     }
  3101.   },
  3102.  
  3103.   observe: function(aSubject, aTopic, aData)
  3104.   {
  3105.     if (aData == "browser.fullscreen.autohide") {
  3106.       if (gPrefService.getBoolPref("browser.fullscreen.autohide")) {
  3107.         gBrowser.mPanelContainer.addEventListener("mousemove",
  3108.                                                   this._collapseCallback, false);
  3109.       }
  3110.       else {
  3111.         gBrowser.mPanelContainer.removeEventListener("mousemove",
  3112.                                                      this._collapseCallback, false);
  3113.       }
  3114.     }
  3115.   },
  3116.  
  3117.   // Event callbacks
  3118.   _expandCallback: function()
  3119.   {
  3120.     FullScreen.mouseoverToggle(true);
  3121.   },
  3122.   _collapseCallback: function()
  3123.   {
  3124.     FullScreen.mouseoverToggle(false);
  3125.   },
  3126.   _keyToggleCallback: function(aEvent)
  3127.   {
  3128.     // if we can use the keyboard (eg Ctrl+L or Ctrl+E) to open the toolbars, we
  3129.     // should provide a way to collapse them too.
  3130.     if (aEvent.keyCode == aEvent.DOM_VK_ESCAPE) {
  3131.       FullScreen._shouldAnimate = false;
  3132.       FullScreen.mouseoverToggle(false, true);
  3133.     }
  3134.     // F6 is another shortcut to the address bar, but its not covered in OpenLocation()
  3135.     else if (aEvent.keyCode == aEvent.DOM_VK_F6)
  3136.       FullScreen.mouseoverToggle(true);
  3137.   },
  3138.  
  3139.   // Checks whether we are allowed to collapse the chrome
  3140.   _isPopupOpen: false,
  3141.   _isChromeCollapsed: false,
  3142.   _safeToCollapse: function(forceHide)
  3143.   {
  3144.     if (!gPrefService.getBoolPref("browser.fullscreen.autohide"))
  3145.       return false;
  3146.  
  3147.     // a popup menu is open in chrome: don't collapse chrome
  3148.     if (!forceHide && this._isPopupOpen)
  3149.       return false;
  3150.  
  3151.     // a textbox in chrome is focused (location bar anyone?): don't collapse chrome
  3152.     if (document.commandDispatcher.focusedElement &&
  3153.         document.commandDispatcher.focusedElement.ownerDocument == document &&
  3154.         document.commandDispatcher.focusedElement.localName == "input") {
  3155.       if (forceHide)
  3156.         // hidden textboxes that still have focus are bad bad bad
  3157.         document.commandDispatcher.focusedElement.blur();
  3158.       else
  3159.         return false;
  3160.     }
  3161.     return true;
  3162.   },
  3163.  
  3164.   _setPopupOpen: function(aEvent)
  3165.   {
  3166.     // Popups should only veto chrome collapsing if they were opened when the chrome was not collapsed.
  3167.     // Otherwise, they would not affect chrome and the user would expect the chrome to go away.
  3168.     // e.g. we wouldn't want the autoscroll icon firing this event, so when the user
  3169.     // toggles chrome when moving mouse to the top, it doesn't go away again.
  3170.     if (aEvent.type == "popupshown" && !FullScreen._isChromeCollapsed &&
  3171.         aEvent.target.localName != "tooltip" && aEvent.target.localName != "window")
  3172.       FullScreen._isPopupOpen = true;
  3173.     else if (aEvent.type == "popuphidden" && aEvent.target.localName != "tooltip" &&
  3174.              aEvent.target.localName != "window")
  3175.       FullScreen._isPopupOpen = false;
  3176.   },
  3177.  
  3178.   // Autohide helpers for the context menu item
  3179.   getAutohide: function(aItem)
  3180.   {
  3181.     aItem.setAttribute("checked", gPrefService.getBoolPref("browser.fullscreen.autohide"));
  3182.   },
  3183.   setAutohide: function()
  3184.   {
  3185.     gPrefService.setBoolPref("browser.fullscreen.autohide", !gPrefService.getBoolPref("browser.fullscreen.autohide"));
  3186.   },
  3187.  
  3188.   // Animate the toolbars disappearing
  3189.   _shouldAnimate: true,
  3190.   _isAnimating: false,
  3191.   _animationTimeout: null,
  3192.   _animationInterval: null,
  3193.   _animateUp: function()
  3194.   {
  3195.     // check again, the user may have done something before the animation was due to start
  3196.     if (!window.fullScreen || !FullScreen._safeToCollapse(false)) {
  3197.       FullScreen._isAnimating = false;
  3198.       FullScreen._shouldAnimate = true;
  3199.       return;
  3200.     }
  3201.  
  3202.     var navToolbox = getNavToolbox();
  3203.     var animateFrameAmount = 2;
  3204.     function animateUpFrame() {
  3205.       animateFrameAmount *= 2;
  3206.       if (animateFrameAmount >=
  3207.           (navToolbox.boxObject.height + gBrowser.mStrip.boxObject.height)) {
  3208.         // We've animated enough
  3209.         clearInterval(FullScreen._animationInterval);
  3210.         navToolbox.style.marginTop = "0px";
  3211.         FullScreen._isAnimating = false;
  3212.         FullScreen._shouldAnimate = false; // Just to make sure
  3213.         FullScreen.mouseoverToggle(false);
  3214.         return;
  3215.       }
  3216.       navToolbox.style.marginTop = (animateFrameAmount * -1) + "px";
  3217.     }
  3218.  
  3219.     FullScreen._animationInterval = setInterval(animateUpFrame, 70);
  3220.   },
  3221.  
  3222.   mouseoverToggle: function(aShow, forceHide)
  3223.   {
  3224.     // Don't do anything if:
  3225.     // a) we're already in the state we want,
  3226.     // b) we're animating and will become collapsed soon, or
  3227.     // c) we can't collapse because it would be undesirable right now
  3228.     if (aShow != this._isChromeCollapsed || (!aShow && this._isAnimating) ||
  3229.         (!aShow && !this._safeToCollapse(forceHide)))
  3230.       return;
  3231.  
  3232.     // browser.fullscreen.animateUp
  3233.     // 0 - never animate up
  3234.     // 1 - animate only for first collapse after entering fullscreen (default for perf's sake)
  3235.     // 2 - animate every time it collapses
  3236.     if (gPrefService.getIntPref("browser.fullscreen.animateUp") == 0)
  3237.       this._shouldAnimate = false;
  3238.  
  3239.     if (!aShow && this._shouldAnimate) {
  3240.       this._isAnimating = true;
  3241.       this._shouldAnimate = false;
  3242.       this._animationTimeout = setTimeout(this._animateUp, 800);
  3243.       return;
  3244.     }
  3245.  
  3246.     // The chrome is collapsed so don't spam needless mousemove events
  3247.     if (aShow) {
  3248.       gBrowser.mPanelContainer.addEventListener("mousemove",
  3249.                                                 this._collapseCallback, false);
  3250.     }
  3251.     else {
  3252.       gBrowser.mPanelContainer.removeEventListener("mousemove",
  3253.                                                    this._collapseCallback, false);
  3254.     }
  3255.  
  3256.     gBrowser.mStrip.setAttribute("moz-collapsed", !aShow);
  3257.     var allFSToolbars = document.getElementsByTagNameNS(this._XULNS, "toolbar");
  3258.     for (var i = 0; i < allFSToolbars.length; i++) {
  3259.       if (allFSToolbars[i].getAttribute("fullscreentoolbar") == "true")
  3260.         allFSToolbars[i].setAttribute("moz-collapsed", !aShow);
  3261.     }
  3262.     document.getElementById("fullscr-toggler").setAttribute("moz-collapsed", aShow);
  3263.     this._isChromeCollapsed = !aShow;
  3264.     if (gPrefService.getIntPref("browser.fullscreen.animateUp") == 2)
  3265.       this._shouldAnimate = true;
  3266.   },
  3267.  
  3268.   showXULChrome: function(aTag, aShow)
  3269.   {
  3270.     var els = document.getElementsByTagNameNS(this._XULNS, aTag);
  3271.  
  3272.     for (var i = 0; i < els.length; ++i) {
  3273.       // XXX don't interfere with previously collapsed toolbars
  3274.       if (els[i].getAttribute("fullscreentoolbar") == "true") {
  3275.         if (!aShow) {
  3276.  
  3277.           var toolbarMode = els[i].getAttribute("mode");
  3278.           if (toolbarMode != "text") {
  3279.             els[i].setAttribute("saved-mode", toolbarMode);
  3280.             els[i].setAttribute("saved-iconsize",
  3281.                                 els[i].getAttribute("iconsize"));
  3282.             els[i].setAttribute("mode", "icons");
  3283.             els[i].setAttribute("iconsize", "small");
  3284.           }
  3285.  
  3286.           // Give the main nav bar the fullscreen context menu, otherwise remove it
  3287.           // to prevent breakage
  3288.           els[i].setAttribute("saved-context",
  3289.                               els[i].getAttribute("context"));
  3290.           if (els[i].id == "nav-bar")
  3291.             els[i].setAttribute("context", "autohide-context");
  3292.           else
  3293.             els[i].removeAttribute("context");
  3294.  
  3295.           // Set the inFullscreen attribute to allow specific styling
  3296.           // in fullscreen mode
  3297.           els[i].setAttribute("inFullscreen", true);
  3298.         }
  3299.         else {
  3300.           function restoreAttr(attrName) {
  3301.             var savedAttr = "saved-" + attrName;
  3302.             if (els[i].hasAttribute(savedAttr)) {
  3303.               els[i].setAttribute(attrName, els[i].getAttribute(savedAttr));
  3304.               els[i].removeAttribute(savedAttr);
  3305.             }
  3306.           }
  3307.  
  3308.           restoreAttr("mode");
  3309.           restoreAttr("iconsize");
  3310.           restoreAttr("context");
  3311.  
  3312.           els[i].removeAttribute("inFullscreen");
  3313.         }
  3314.       } else {
  3315.         // use moz-collapsed so it doesn't persist hidden/collapsed,
  3316.         // so that new windows don't have missing toolbars
  3317.         if (aShow)
  3318.           els[i].removeAttribute("moz-collapsed");
  3319.         else
  3320.           els[i].setAttribute("moz-collapsed", "true");
  3321.       }
  3322.     }
  3323.  
  3324.     var toolbox = getNavToolbox();
  3325.     if (aShow)
  3326.       toolbox.removeAttribute("inFullscreen");
  3327.     else
  3328.       toolbox.setAttribute("inFullscreen", true);
  3329.  
  3330. //@line 3692 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  3331.     var controls = document.getElementsByAttribute("fullscreencontrol", "true");
  3332.     for (var i = 0; i < controls.length; ++i)
  3333.       controls[i].hidden = aShow;
  3334. //@line 3696 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  3335.   }
  3336. };
  3337.  
  3338. /**
  3339.  * Returns true if |aMimeType| is text-based, false otherwise.
  3340.  *
  3341.  * @param aMimeType
  3342.  *        The MIME type to check.
  3343.  *
  3344.  * If adding types to this function, please also check the similar 
  3345.  * function in findbar.xml
  3346.  */
  3347. function mimeTypeIsTextBased(aMimeType)
  3348. {
  3349.   return /^text\/|\+xml$/.test(aMimeType) ||
  3350.          aMimeType == "application/x-javascript" ||
  3351.          aMimeType == "application/javascript" ||
  3352.          aMimeType == "application/xml" ||
  3353.          aMimeType == "mozilla.application/cached-xul";
  3354. }
  3355.  
  3356. function nsBrowserStatusHandler()
  3357. {
  3358.   this.init();
  3359. }
  3360.  
  3361. nsBrowserStatusHandler.prototype =
  3362. {
  3363.   // Stored Status, Link and Loading values
  3364.   status : "",
  3365.   defaultStatus : "",
  3366.   jsStatus : "",
  3367.   jsDefaultStatus : "",
  3368.   overLink : "",
  3369.   startTime : 0,
  3370.   statusText: "",
  3371.   lastURI: null,
  3372.  
  3373.   statusTimeoutInEffect : false,
  3374.  
  3375.   QueryInterface : function(aIID)
  3376.   {
  3377.     if (aIID.equals(Ci.nsIWebProgressListener) ||
  3378.         aIID.equals(Ci.nsIWebProgressListener2) ||
  3379.         aIID.equals(Ci.nsISupportsWeakReference) ||
  3380.         aIID.equals(Ci.nsIXULBrowserWindow) ||
  3381.         aIID.equals(Ci.nsISupports))
  3382.       return this;
  3383.     throw Cr.NS_NOINTERFACE;
  3384.   },
  3385.  
  3386.   init : function()
  3387.   {
  3388.     this.throbberElement        = document.getElementById("navigator-throbber");
  3389.     this.statusMeter            = document.getElementById("statusbar-icon");
  3390.     this.stopCommand            = document.getElementById("Browser:Stop");
  3391.     this.reloadCommand          = document.getElementById("Browser:Reload");
  3392.     this.reloadSkipCacheCommand = document.getElementById("Browser:ReloadSkipCache");
  3393.     this.statusTextField        = document.getElementById("statusbar-display");
  3394.     this.securityButton         = document.getElementById("security-button");
  3395.     this.urlBar                 = document.getElementById("urlbar");
  3396.     this.isImage                = document.getElementById("isImage");
  3397.  
  3398.     // Initialize the security button's state and tooltip text.  Remember to reset
  3399.     // _hostChanged, otherwise onSecurityChange will short circuit.
  3400.     var securityUI = getBrowser().securityUI;
  3401.     this._hostChanged = true;
  3402.     this.onSecurityChange(null, null, securityUI.state);
  3403.   },
  3404.  
  3405.   destroy : function()
  3406.   {
  3407.     // XXXjag to avoid leaks :-/, see bug 60729
  3408.     this.throbberElement        = null;
  3409.     this.statusMeter            = null;
  3410.     this.stopCommand            = null;
  3411.     this.reloadCommand          = null;
  3412.     this.reloadSkipCacheCommand = null;
  3413.     this.statusTextField        = null;
  3414.     this.securityButton         = null;
  3415.     this.urlBar                 = null;
  3416.     this.statusText             = null;
  3417.     this.lastURI                = null;
  3418.   },
  3419.  
  3420.   setJSStatus : function(status)
  3421.   {
  3422.     this.jsStatus = status;
  3423.     this.updateStatusField();
  3424.   },
  3425.  
  3426.   setJSDefaultStatus : function(status)
  3427.   {
  3428.     this.jsDefaultStatus = status;
  3429.     this.updateStatusField();
  3430.   },
  3431.  
  3432.   setDefaultStatus : function(status)
  3433.   {
  3434.     this.defaultStatus = status;
  3435.     this.updateStatusField();
  3436.   },
  3437.  
  3438.   setOverLink : function(link, b)
  3439.   {
  3440.     // Encode bidirectional formatting characters.
  3441.     // (RFC 3987 sections 3.2 and 4.1 paragraph 6)
  3442.     this.overLink = link.replace(/[\u200e\u200f\u202a\u202b\u202c\u202d\u202e]/g,
  3443.                                  encodeURIComponent);
  3444.     this.updateStatusField();
  3445.   },
  3446.  
  3447.   updateStatusField : function()
  3448.   {
  3449.     var text = this.overLink || this.status || this.jsStatus || this.jsDefaultStatus || this.defaultStatus;
  3450.  
  3451.     // check the current value so we don't trigger an attribute change
  3452.     // and cause needless (slow!) UI updates
  3453.     if (this.statusText != text) {
  3454.       this.statusTextField.label = text;
  3455.       this.statusText = text;
  3456.     }
  3457.   },
  3458.   
  3459.   onLinkIconAvailable : function(aBrowser)
  3460.   {
  3461.     if (gProxyFavIcon && gBrowser.mCurrentBrowser == aBrowser &&
  3462.         gBrowser.userTypedValue === null)
  3463.       PageProxySetIcon(aBrowser.mIconURL); // update the favicon in the URL bar
  3464.   },
  3465.  
  3466.   onProgressChange : function (aWebProgress, aRequest,
  3467.                                aCurSelfProgress, aMaxSelfProgress,
  3468.                                aCurTotalProgress, aMaxTotalProgress)
  3469.   {
  3470.     if (aMaxTotalProgress > 0) {
  3471.       // This is highly optimized.  Don't touch this code unless
  3472.       // you are intimately familiar with the cost of setting
  3473.       // attrs on XUL elements. -- hyatt
  3474.       var percentage = (aCurTotalProgress * 100) / aMaxTotalProgress;
  3475.       this.statusMeter.value = percentage;
  3476.     }
  3477.   },
  3478.  
  3479.   onProgressChange64 : function (aWebProgress, aRequest,
  3480.                                  aCurSelfProgress, aMaxSelfProgress,
  3481.                                  aCurTotalProgress, aMaxTotalProgress)
  3482.   {
  3483.     return this.onProgressChange(aWebProgress, aRequest,
  3484.       aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress,
  3485.       aMaxTotalProgress);
  3486.   },
  3487.  
  3488.   onStateChange : function(aWebProgress, aRequest, aStateFlags, aStatus)
  3489.   {
  3490.     const nsIWebProgressListener = Components.interfaces.nsIWebProgressListener;
  3491.     const nsIChannel = Components.interfaces.nsIChannel;
  3492.     if (aStateFlags & nsIWebProgressListener.STATE_START) {
  3493.         // This (thanks to the filter) is a network start or the first
  3494.         // stray request (the first request outside of the document load),
  3495.         // initialize the throbber and his friends.
  3496.  
  3497.         // Call start document load listeners (only if this is a network load)
  3498.         if (aStateFlags & nsIWebProgressListener.STATE_IS_NETWORK &&
  3499.             aRequest && aWebProgress.DOMWindow == content)
  3500.           this.startDocumentLoad(aRequest);
  3501.  
  3502.         if (this.throbberElement) {
  3503.           // Turn the throbber on.
  3504.           this.throbberElement.setAttribute("busy", "true");
  3505.         }
  3506.  
  3507.         // Turn the status meter on.
  3508.         this.statusMeter.value = 0;  // be sure to clear the progress bar
  3509.         if (gProgressCollapseTimer) {
  3510.           window.clearTimeout(gProgressCollapseTimer);
  3511.           gProgressCollapseTimer = null;
  3512.         }
  3513.         else
  3514.           this.statusMeter.parentNode.collapsed = false;
  3515.  
  3516.         // XXX: This needs to be based on window activity...
  3517.         this.stopCommand.removeAttribute("disabled");
  3518.     }
  3519.     else if (aStateFlags & nsIWebProgressListener.STATE_STOP) {
  3520.       if (aStateFlags & nsIWebProgressListener.STATE_IS_NETWORK) {
  3521.         if (aWebProgress.DOMWindow == content) {
  3522.           if (aRequest)
  3523.             this.endDocumentLoad(aRequest, aStatus);
  3524.           var browser = gBrowser.mCurrentBrowser;
  3525.           if (!gBrowser.mTabbedMode && !browser.mIconURL)
  3526.             gBrowser.useDefaultIcon(gBrowser.mCurrentTab);
  3527.  
  3528.           if (Components.isSuccessCode(aStatus) &&
  3529.               content.document.documentElement.getAttribute("manifest")) {
  3530.             OfflineApps.offlineAppRequested(content);
  3531.           }
  3532.         }
  3533.       }
  3534.  
  3535.       // This (thanks to the filter) is a network stop or the last
  3536.       // request stop outside of loading the document, stop throbbers
  3537.       // and progress bars and such
  3538.       if (aRequest) {
  3539.         var msg = "";
  3540.           // Get the URI either from a channel or a pseudo-object
  3541.           if (aRequest instanceof nsIChannel || "URI" in aRequest) {
  3542.             var location = aRequest.URI;
  3543.  
  3544.             // For keyword URIs clear the user typed value since they will be changed into real URIs
  3545.             if (location.scheme == "keyword" && aWebProgress.DOMWindow == content)
  3546.               getBrowser().userTypedValue = null;
  3547.  
  3548.             if (location.spec != "about:blank") {
  3549.               const kErrorBindingAborted = 0x804B0002;
  3550.               const kErrorNetTimeout = 0x804B000E;
  3551.               switch (aStatus) {
  3552.                 case kErrorBindingAborted:
  3553.                   msg = gNavigatorBundle.getString("nv_stopped");
  3554.                   break;
  3555.                 case kErrorNetTimeout:
  3556.                   msg = gNavigatorBundle.getString("nv_timeout");
  3557.                   break;
  3558.               }
  3559.             }
  3560.           }
  3561.           // If msg is false then we did not have an error (channel may have
  3562.           // been null, in the case of a stray image load).
  3563.           if (!msg && (!location || location.spec != "about:blank")) {
  3564.             msg = gNavigatorBundle.getString("nv_done");
  3565.           }
  3566.           this.status = "";
  3567.           this.setDefaultStatus(msg);
  3568.  
  3569.           // Disable menu entries for images, enable otherwise
  3570.           if (content.document && mimeTypeIsTextBased(content.document.contentType))
  3571.             this.isImage.removeAttribute('disabled');
  3572.           else
  3573.             this.isImage.setAttribute('disabled', 'true');
  3574.         }
  3575.  
  3576.         // Turn the progress meter and throbber off.
  3577.         gProgressCollapseTimer = window.setTimeout(
  3578.           function() {
  3579.             gProgressMeterPanel.collapsed = true;
  3580.             gProgressCollapseTimer = null;
  3581.           }, 100);
  3582.  
  3583.         if (this.throbberElement)
  3584.           this.throbberElement.removeAttribute("busy");
  3585.  
  3586.         this.stopCommand.setAttribute("disabled", "true");
  3587.     }
  3588.   },
  3589.  
  3590.   onLocationChange : function(aWebProgress, aRequest, aLocationURI)
  3591.   {
  3592.     var location = aLocationURI ? aLocationURI.spec : "";
  3593.     this._hostChanged = true;
  3594.  
  3595.     if (document.tooltipNode) {
  3596.       // Optimise for the common case
  3597.       if (aWebProgress.DOMWindow == content) {
  3598.         document.getElementById("aHTMLTooltip").hidePopup();
  3599.         document.tooltipNode = null;
  3600.       }
  3601.       else {
  3602.         for (var tooltipWindow =
  3603.                document.tooltipNode.ownerDocument.defaultView;
  3604.              tooltipWindow != tooltipWindow.parent;
  3605.              tooltipWindow = tooltipWindow.parent) {
  3606.           if (tooltipWindow == aWebProgress.DOMWindow) {
  3607.             document.getElementById("aHTMLTooltip").hidePopup();
  3608.             document.tooltipNode = null;
  3609.             break;
  3610.           }
  3611.         }
  3612.       }
  3613.     }
  3614.  
  3615.     // This code here does not compare uris exactly when determining
  3616.     // whether or not the message should be hidden since the message
  3617.     // may be prematurely hidden when an install is invoked by a click
  3618.     // on a link that looks like this:
  3619.     //
  3620.     // <a href="#" onclick="return install();">Install Foo</a>
  3621.     //
  3622.     // - which fires a onLocationChange message to uri + '#'...
  3623.     var selectedBrowser = getBrowser().selectedBrowser;
  3624.     if (selectedBrowser.lastURI) {
  3625.       var oldSpec = selectedBrowser.lastURI.spec;
  3626.       var oldIndexOfHash = oldSpec.indexOf("#");
  3627.       if (oldIndexOfHash != -1)
  3628.         oldSpec = oldSpec.substr(0, oldIndexOfHash);
  3629.       var newSpec = location;
  3630.       var newIndexOfHash = newSpec.indexOf("#");
  3631.       if (newIndexOfHash != -1)
  3632.         newSpec = newSpec.substr(0, newSpec.indexOf("#"));
  3633.       if (newSpec != oldSpec) {
  3634.         // Remove all the notifications, except for those which want to
  3635.         // persist across the first location change.
  3636.         var nBox = gBrowser.getNotificationBox(selectedBrowser);
  3637.         nBox.removeTransientNotifications();
  3638.       }
  3639.     }
  3640.     selectedBrowser.lastURI = aLocationURI;
  3641.  
  3642.     // Disable menu entries for images, enable otherwise
  3643.     if (content.document && mimeTypeIsTextBased(content.document.contentType))
  3644.       this.isImage.removeAttribute('disabled');
  3645.     else
  3646.       this.isImage.setAttribute('disabled', 'true');
  3647.  
  3648.     this.setOverLink("", null);
  3649.  
  3650.     // We should probably not do this if the value has changed since the user
  3651.     // searched
  3652.     // Update urlbar only if a new page was loaded on the primary content area
  3653.     // Do not update urlbar if there was a subframe navigation
  3654.  
  3655.     var browser = getBrowser().selectedBrowser;
  3656.     if (aWebProgress.DOMWindow == content) {
  3657.  
  3658.       if ((location == "about:blank" && !content.opener) ||
  3659.            location == "") {  // Second condition is for new tabs, otherwise
  3660.                               // reload function is enabled until tab is refreshed.
  3661.         this.reloadCommand.setAttribute("disabled", "true");
  3662.         this.reloadSkipCacheCommand.setAttribute("disabled", "true");
  3663.       } else {
  3664.         this.reloadCommand.removeAttribute("disabled");
  3665.         this.reloadSkipCacheCommand.removeAttribute("disabled");
  3666.       }
  3667.  
  3668.       if (!gBrowser.mTabbedMode && aWebProgress.isLoadingDocument)
  3669.         gBrowser.setIcon(gBrowser.mCurrentTab, null);
  3670.  
  3671.       if (gURLBar) {
  3672.         URLBarSetURI(aLocationURI);
  3673.  
  3674.         // Update starring UI
  3675.         PlacesStarButton.updateState();
  3676.       }
  3677.     }
  3678.     UpdateBackForwardCommands(gBrowser.webNavigation);
  3679.  
  3680.     if (gFindBar.findMode != gFindBar.FIND_NORMAL) {
  3681.       // Close the Find toolbar if we're in old-style TAF mode
  3682.       gFindBar.close();
  3683.     }
  3684.  
  3685.     // XXXmano new-findbar, do something useful once it lands.
  3686.     // Of course, this is especially wrong with bfcache on...
  3687.  
  3688.     // fix bug 253793 - turn off highlight when page changes
  3689.     gFindBar.getElement("highlight").checked = false;
  3690.  
  3691.     // See bug 358202, when tabs are switched during a drag operation,
  3692.     // timers don't fire on windows (bug 203573)
  3693.     if (aRequest) {
  3694.       var self = this;
  3695.       setTimeout(function() { self.asyncUpdateUI(); }, 0);
  3696.     } 
  3697.     else
  3698.       this.asyncUpdateUI();
  3699.  
  3700.     // Catch exceptions until bug 376222 gets fixed so we don't hork
  3701.     // other progress listeners if this call throws an exception.
  3702.     try {
  3703.       FullZoom.onLocationChange(aLocationURI);
  3704.     }
  3705.     catch(ex) {
  3706.       Components.utils.reportError(ex);
  3707.     }
  3708.   },
  3709.   
  3710.   asyncUpdateUI : function () {
  3711.     FeedHandler.updateFeeds();
  3712.     BrowserSearch.updateSearchButton();
  3713.   },
  3714.  
  3715.   onStatusChange : function(aWebProgress, aRequest, aStatus, aMessage)
  3716.   {
  3717.     this.status = aMessage;
  3718.     this.updateStatusField();
  3719.   },
  3720.  
  3721.   onRefreshAttempted : function(aWebProgress, aURI, aDelay, aSameURI)
  3722.   {
  3723.     if (gPrefService.getBoolPref("accessibility.blockautorefresh")) {
  3724.       var brandBundle = document.getElementById("bundle_brand");
  3725.       var brandShortName = brandBundle.getString("brandShortName");
  3726.       var refreshButtonText = 
  3727.         gNavigatorBundle.getString("refreshBlocked.goButton");
  3728.       var refreshButtonAccesskey = 
  3729.         gNavigatorBundle.getString("refreshBlocked.goButton.accesskey");
  3730.       var message;
  3731.       if (aSameURI)
  3732.         message = gNavigatorBundle.getFormattedString(
  3733.           "refreshBlocked.refreshLabel", [brandShortName]);
  3734.       else
  3735.         message = gNavigatorBundle.getFormattedString(
  3736.           "refreshBlocked.redirectLabel", [brandShortName]);
  3737.       var topBrowser = getBrowserFromContentWindow(aWebProgress.DOMWindow.top);
  3738.       var docShell = aWebProgress.DOMWindow
  3739.                                  .QueryInterface(Ci.nsIInterfaceRequestor)
  3740.                                  .getInterface(Ci.nsIWebNavigation)
  3741.                                  .QueryInterface(Ci.nsIDocShell);
  3742.       var notificationBox = gBrowser.getNotificationBox(topBrowser);
  3743.       var notification = notificationBox.getNotificationWithValue(
  3744.         "refresh-blocked");
  3745.       if (notification) {
  3746.         notification.label = message;
  3747.         notification.refreshURI = aURI;
  3748.         notification.delay = aDelay;
  3749.         notification.docShell = docShell;
  3750.       }
  3751.       else {
  3752.         var buttons = [{
  3753.           label: refreshButtonText,
  3754.           accessKey: refreshButtonAccesskey,
  3755.           callback: function(aNotification, aButton) {
  3756.             var refreshURI = aNotification.docShell
  3757.                                           .QueryInterface(Ci.nsIRefreshURI);
  3758.             refreshURI.forceRefreshURI(aNotification.refreshURI,
  3759.                                        aNotification.delay, true);
  3760.           }
  3761.         }];
  3762.         const priority = notificationBox.PRIORITY_INFO_MEDIUM;
  3763.         notification = notificationBox.appendNotification(
  3764.           message,
  3765.           "refresh-blocked",
  3766.           "chrome://browser/skin/Info.png",
  3767.           priority,
  3768.           buttons);
  3769.         notification.refreshURI = aURI;
  3770.         notification.delay = aDelay;
  3771.         notification.docShell = docShell;
  3772.       }
  3773.       return false;
  3774.     }
  3775.     return true;
  3776.   },
  3777.  
  3778.   // Properties used to cache security state used to update the UI
  3779.   _state: null,
  3780.   _host: undefined,
  3781.   _tooltipText: null,
  3782.   _hostChanged: false, // onLocationChange will flip this bit
  3783.  
  3784.   onSecurityChange : function browser_onSecChange(aWebProgress,
  3785.                                                   aRequest, aState)
  3786.   {
  3787.     // Don't need to do anything if the data we use to update the UI hasn't
  3788.     // changed
  3789.     if (this._state == aState &&
  3790.         this._tooltipText == gBrowser.securityUI.tooltipText &&
  3791.         !this._hostChanged) {
  3792. //@line 4164 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  3793.       return;
  3794.     }
  3795.     this._state = aState;
  3796.  
  3797.     try {
  3798.       this._host = gBrowser.contentWindow.location.host;
  3799.     } catch(ex) {
  3800.       this._host = null;
  3801.     }
  3802.  
  3803.     this._hostChanged = false;
  3804.     this._tooltipText = gBrowser.securityUI.tooltipText
  3805.  
  3806.     // aState is defined as a bitmask that may be extended in the future.
  3807.     // We filter out any unknown bits before testing for known values.
  3808.     const wpl = Components.interfaces.nsIWebProgressListener;
  3809.     const wpl_security_bits = wpl.STATE_IS_SECURE |
  3810.                               wpl.STATE_IS_BROKEN |
  3811.                               wpl.STATE_IS_INSECURE |
  3812.                               wpl.STATE_SECURE_HIGH |
  3813.                               wpl.STATE_SECURE_MED |
  3814.                               wpl.STATE_SECURE_LOW;
  3815.     var level = null;
  3816.     var setHost = false;
  3817.  
  3818.     switch (this._state & wpl_security_bits) {
  3819.       case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_HIGH:
  3820.         level = "high";
  3821.         setHost = true;
  3822.         break;
  3823.       case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_MED:
  3824.       case wpl.STATE_IS_SECURE | wpl.STATE_SECURE_LOW:
  3825.         level = "low";
  3826.         setHost = true;
  3827.         break;
  3828.       case wpl.STATE_IS_BROKEN:
  3829.         level = "broken";
  3830.         break;
  3831.     }
  3832.  
  3833.     if (level) {
  3834.       this.securityButton.setAttribute("level", level);
  3835.       if (this.urlBar)
  3836.         this.urlBar.setAttribute("level", level);    
  3837.     } else {
  3838.       this.securityButton.removeAttribute("level");
  3839.       if (this.urlBar)
  3840.         this.urlBar.removeAttribute("level");
  3841.     }
  3842.  
  3843.     if (setHost && this._host)
  3844.       this.securityButton.setAttribute("label", this._host);
  3845.     else
  3846.       this.securityButton.removeAttribute("label");
  3847.  
  3848.     this.securityButton.setAttribute("tooltiptext", this._tooltipText);
  3849.  
  3850.     // Don't pass in the actual location object, since it can cause us to 
  3851.     // hold on to the window object too long.  Just pass in the fields we
  3852.     // care about. (bug 424829)
  3853.     var location = gBrowser.contentWindow.location;
  3854.     var locationObj = {};
  3855.     try {
  3856.       locationObj.host = location.host;
  3857.       locationObj.hostname = location.hostname;
  3858.       locationObj.port = location.port;
  3859.     } catch (ex) {
  3860.       // Can sometimes throw if the URL being visited has no host/hostname,
  3861.       // e.g. about:blank. The _state for these pages means we won't need these
  3862.       // properties anyways, though.
  3863.     }
  3864.     getIdentityHandler().checkIdentity(this._state, locationObj);
  3865.   },
  3866.  
  3867.   // simulate all change notifications after switching tabs
  3868.   onUpdateCurrentBrowser : function(aStateFlags, aStatus, aMessage, aTotalProgress)
  3869.   {
  3870.     var nsIWebProgressListener = Components.interfaces.nsIWebProgressListener;
  3871.     var loadingDone = aStateFlags & nsIWebProgressListener.STATE_STOP;
  3872.     // use a pseudo-object instead of a (potentially non-existing) channel for getting
  3873.     // a correct error message - and make sure that the UI is always either in
  3874.     // loading (STATE_START) or done (STATE_STOP) mode
  3875.     this.onStateChange(
  3876.       gBrowser.webProgress,
  3877.       { URI: gBrowser.currentURI },
  3878.       loadingDone ? nsIWebProgressListener.STATE_STOP : nsIWebProgressListener.STATE_START,
  3879.       aStatus
  3880.     );
  3881.     // status message and progress value are undefined if we're done with loading
  3882.     if (loadingDone)
  3883.       return;
  3884.     this.onStatusChange(gBrowser.webProgress, null, 0, aMessage);
  3885.     this.onProgressChange(gBrowser.webProgress, 0, 0, aTotalProgress, 1);
  3886.   },
  3887.  
  3888.   startDocumentLoad : function(aRequest)
  3889.   {
  3890.     // clear out feed data
  3891.     gBrowser.mCurrentBrowser.feeds = null;
  3892.  
  3893.     // clear out search-engine data
  3894.     gBrowser.mCurrentBrowser.engines = null;    
  3895.  
  3896.     const nsIChannel = Components.interfaces.nsIChannel;
  3897.     var urlStr = aRequest.QueryInterface(nsIChannel).URI.spec;
  3898.     var observerService = Components.classes["@mozilla.org/observer-service;1"]
  3899.                                     .getService(Components.interfaces.nsIObserverService);
  3900.     try {
  3901.       observerService.notifyObservers(content, "StartDocumentLoad", urlStr);
  3902.     } catch (e) {
  3903.     }
  3904.   },
  3905.  
  3906.   endDocumentLoad : function(aRequest, aStatus)
  3907.   {
  3908.     const nsIChannel = Components.interfaces.nsIChannel;
  3909.     var urlStr = aRequest.QueryInterface(nsIChannel).originalURI.spec;
  3910.  
  3911.     var observerService = Components.classes["@mozilla.org/observer-service;1"]
  3912.                                     .getService(Components.interfaces.nsIObserverService);
  3913.  
  3914.     var notification = Components.isSuccessCode(aStatus) ? "EndDocumentLoad" : "FailDocumentLoad";
  3915.     try {
  3916.       observerService.notifyObservers(content, notification, urlStr);
  3917.     } catch (e) {
  3918.     }
  3919.   }
  3920. }
  3921.  
  3922. function nsBrowserAccess()
  3923. {
  3924. }
  3925.  
  3926. nsBrowserAccess.prototype =
  3927. {
  3928.   QueryInterface : function(aIID)
  3929.   {
  3930.     if (aIID.equals(Ci.nsIBrowserDOMWindow) ||
  3931.         aIID.equals(Ci.nsISupports))
  3932.       return this;
  3933.     throw Components.results.NS_NOINTERFACE;
  3934.   },
  3935.  
  3936.   openURI : function(aURI, aOpener, aWhere, aContext)
  3937.   {
  3938.     var newWindow = null;
  3939.     var referrer = null;
  3940.     var isExternal = (aContext == Ci.nsIBrowserDOMWindow.OPEN_EXTERNAL);
  3941.  
  3942.     if (isExternal && aURI && aURI.schemeIs("chrome")) {
  3943.       dump("use -chrome command-line option to load external chrome urls\n");
  3944.       return null;
  3945.     }
  3946.  
  3947.     if (!gPrefService)
  3948.       gPrefService = Components.classes["@mozilla.org/preferences-service;1"]
  3949.                                .getService(Components.interfaces.nsIPrefBranch2);
  3950.  
  3951.     var loadflags = isExternal ?
  3952.                        Ci.nsIWebNavigation.LOAD_FLAGS_FROM_EXTERNAL :
  3953.                        Ci.nsIWebNavigation.LOAD_FLAGS_NONE;
  3954.     var location;
  3955.     if (aWhere == Ci.nsIBrowserDOMWindow.OPEN_DEFAULTWINDOW) {
  3956.       switch (aContext) {
  3957.         case Ci.nsIBrowserDOMWindow.OPEN_EXTERNAL :
  3958.           aWhere = gPrefService.getIntPref("browser.link.open_external");
  3959.           break;
  3960.         default : // OPEN_NEW or an illegal value
  3961.           aWhere = gPrefService.getIntPref("browser.link.open_newwindow");
  3962.       }
  3963.     }
  3964.     switch(aWhere) {
  3965.       case Ci.nsIBrowserDOMWindow.OPEN_NEWWINDOW :
  3966.         // FIXME: Bug 408379. So how come this doesn't send the
  3967.         // referrer like the other loads do?
  3968.         var url = aURI ? aURI.spec : "about:blank";
  3969.         // Pass all params to openDialog to ensure that "url" isn't passed through
  3970.         // loadOneOrMoreURIs, which splits based on "|"
  3971.         newWindow = openDialog(getBrowserURL(), "_blank", "all,dialog=no", url, null, null, null);
  3972.         break;
  3973.       case Ci.nsIBrowserDOMWindow.OPEN_NEWTAB :
  3974.         var win = this._getMostRecentBrowserWindow();
  3975.         if (!win) {
  3976.           // we couldn't find a suitable window, a new one needs to be opened.
  3977.           return null;
  3978.         }
  3979.         var loadInBackground = gPrefService.getBoolPref("browser.tabs.loadDivertedInBackground");
  3980.         var newTab = win.gBrowser.loadOneTab("about:blank", null, null, null, loadInBackground, false);
  3981.         newWindow = win.gBrowser.getBrowserForTab(newTab).docShell
  3982.                                 .QueryInterface(Ci.nsIInterfaceRequestor)
  3983.                                 .getInterface(Ci.nsIDOMWindow);
  3984.         try {
  3985.           if (aURI) {
  3986.             if (aOpener) {
  3987.               location = aOpener.location;
  3988.               referrer =
  3989.                       Components.classes["@mozilla.org/network/io-service;1"]
  3990.                                 .getService(Components.interfaces.nsIIOService)
  3991.                                 .newURI(location, null, null);
  3992.             }
  3993.             newWindow.QueryInterface(Ci.nsIInterfaceRequestor)
  3994.                      .getInterface(Ci.nsIWebNavigation)
  3995.                      .loadURI(aURI.spec, loadflags, referrer, null, null);
  3996.           }
  3997.           if (!loadInBackground && isExternal)
  3998.             newWindow.focus();
  3999.         } catch(e) {
  4000.         }
  4001.         break;
  4002.       default : // OPEN_CURRENTWINDOW or an illegal value
  4003.         try {
  4004.           if (aOpener) {
  4005.             newWindow = aOpener.top;
  4006.             if (aURI) {
  4007.               location = aOpener.location;
  4008.               referrer =
  4009.                       Components.classes["@mozilla.org/network/io-service;1"]
  4010.                                 .getService(Components.interfaces.nsIIOService)
  4011.                                 .newURI(location, null, null);
  4012.  
  4013.               newWindow.QueryInterface(Ci.nsIInterfaceRequestor)
  4014.                        .getInterface(nsIWebNavigation)
  4015.                        .loadURI(aURI.spec, loadflags, referrer, null, null);
  4016.             }
  4017.           } else {
  4018.             newWindow = gBrowser.selectedBrowser.docShell
  4019.                                 .QueryInterface(Ci.nsIInterfaceRequestor)
  4020.                                 .getInterface(Ci.nsIDOMWindow);
  4021.             if (aURI) {
  4022.               gBrowser.loadURIWithFlags(aURI.spec, loadflags, null, 
  4023.                                         null, null);
  4024.             }
  4025.           }
  4026.           if(!gPrefService.getBoolPref("browser.tabs.loadDivertedInBackground"))
  4027.             content.focus();
  4028.         } catch(e) {
  4029.         }
  4030.     }
  4031.     return newWindow;
  4032.   },
  4033.  
  4034. //@line 4413 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  4035.  
  4036.   // this returns the most recent non-popup browser window
  4037.   _getMostRecentBrowserWindow : function ()
  4038.   {
  4039.     if (!window.document.documentElement.getAttribute("chromehidden"))
  4040.       return window;
  4041.  
  4042.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  4043.                        .getService(Components.interfaces.nsIWindowMediator);
  4044.  
  4045. //@line 4438 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  4046.     var windowList = wm.getZOrderDOMWindowEnumerator("navigator:browser", true);
  4047.     if (!windowList.hasMoreElements())
  4048.       return null;
  4049.  
  4050.     var win = windowList.getNext();
  4051.     while (win.document.documentElement.getAttribute("chromehidden")) {
  4052.       if (!windowList.hasMoreElements()) 
  4053.         return null;
  4054.  
  4055.       win = windowList.getNext();
  4056.     }
  4057. //@line 4450 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  4058.  
  4059.     return win;
  4060.   },
  4061.  
  4062.   isTabContentWindow : function(aWindow)
  4063.   {
  4064.     var browsers = gBrowser.browsers;
  4065.     for (var ctr = 0; ctr < browsers.length; ctr++)
  4066.       if (browsers.item(ctr).contentWindow == aWindow)
  4067.         return true;
  4068.     return false;
  4069.   }
  4070. }
  4071.  
  4072. function onViewToolbarsPopupShowing(aEvent)
  4073. {
  4074.   var popup = aEvent.target;
  4075.   var i;
  4076.  
  4077.   // Empty the menu
  4078.   for (i = popup.childNodes.length-1; i >= 0; --i) {
  4079.     var deadItem = popup.childNodes[i];
  4080.     if (deadItem.hasAttribute("toolbarindex"))
  4081.       popup.removeChild(deadItem);
  4082.   }
  4083.  
  4084.   var firstMenuItem = popup.firstChild;
  4085.  
  4086.   var toolbox = getNavToolbox();
  4087.   for (i = 0; i < toolbox.childNodes.length; ++i) {
  4088.     var toolbar = toolbox.childNodes[i];
  4089.     var toolbarName = toolbar.getAttribute("toolbarname");
  4090.     var type = toolbar.getAttribute("type");
  4091.     if (toolbarName && type != "menubar") {
  4092.       var menuItem = document.createElement("menuitem");
  4093.       menuItem.setAttribute("toolbarindex", i);
  4094.       menuItem.setAttribute("type", "checkbox");
  4095.       menuItem.setAttribute("label", toolbarName);
  4096.       menuItem.setAttribute("accesskey", toolbar.getAttribute("accesskey"));
  4097.       menuItem.setAttribute("checked", toolbar.getAttribute("collapsed") != "true");
  4098.       popup.insertBefore(menuItem, firstMenuItem);
  4099.  
  4100.       menuItem.addEventListener("command", onViewToolbarCommand, false);
  4101.     }
  4102.     toolbar = toolbar.nextSibling;
  4103.   }
  4104. }
  4105.  
  4106. function onViewToolbarCommand(aEvent)
  4107. {
  4108.   var toolbox = getNavToolbox();
  4109.   var index = aEvent.originalTarget.getAttribute("toolbarindex");
  4110.   var toolbar = toolbox.childNodes[index];
  4111.  
  4112.   toolbar.collapsed = aEvent.originalTarget.getAttribute("checked") != "true";
  4113.   document.persist(toolbar.id, "collapsed");
  4114. }
  4115.  
  4116. function displaySecurityInfo()
  4117. {
  4118.   BrowserPageInfo(null, "securityTab");
  4119. }
  4120.  
  4121. /**
  4122.  * Opens or closes the sidebar identified by commandID.
  4123.  *
  4124.  * @param commandID a string identifying the sidebar to toggle; see the
  4125.  *                  note below. (Optional if a sidebar is already open.)
  4126.  * @param forceOpen boolean indicating whether the sidebar should be
  4127.  *                  opened regardless of it's current state (optional).
  4128.  * @note
  4129.  * We expect to find a xul:broadcaster element with the specified ID.
  4130.  * The following attributes on that element may be used and/or modified:
  4131.  *  - id           (required) the string to match commandID. The convention
  4132.  *                 is to use this naming scheme: 'view<sidebar-name>Sidebar'.
  4133.  *  - sidebarurl   (required) specifies the URL to load in this sidebar.
  4134.  *  - sidebartitle or label (in that order) specify the title to 
  4135.  *                 display on the sidebar.
  4136.  *  - checked      indicates whether the sidebar is currently displayed.
  4137.  *                 Note that toggleSidebar updates this attribute when
  4138.  *                 it changes the sidebar's visibility.
  4139.  *  - group        this attribute must be set to "sidebar".
  4140.  */
  4141. function toggleSidebar(commandID, forceOpen) {
  4142.  
  4143.   var sidebarBox = document.getElementById("sidebar-box");
  4144.   if (!commandID)
  4145.     commandID = sidebarBox.getAttribute("sidebarcommand");
  4146.  
  4147.   var sidebarBroadcaster = document.getElementById(commandID);
  4148.   var sidebar = document.getElementById("sidebar"); // xul:browser
  4149.   var sidebarTitle = document.getElementById("sidebar-title");
  4150.   var sidebarSplitter = document.getElementById("sidebar-splitter");
  4151.  
  4152.   if (sidebarBroadcaster.getAttribute("checked") == "true") {
  4153.     if (!forceOpen) {
  4154.       sidebarBroadcaster.removeAttribute("checked");
  4155.       sidebarBox.setAttribute("sidebarcommand", "");
  4156.       sidebarTitle.value = "";
  4157.       sidebar.setAttribute("src", "about:blank");
  4158.       sidebarBox.hidden = true;
  4159.       sidebarSplitter.hidden = true;
  4160.       content.focus();
  4161.     } else {
  4162.       fireSidebarFocusedEvent();
  4163.     }
  4164.     return;
  4165.   }
  4166.  
  4167.   // now we need to show the specified sidebar
  4168.  
  4169.   // ..but first update the 'checked' state of all sidebar broadcasters
  4170.   var broadcasters = document.getElementsByAttribute("group", "sidebar");
  4171.   for (var i = 0; i < broadcasters.length; ++i) {
  4172.     // skip elements that observe sidebar broadcasters and random
  4173.     // other elements
  4174.     if (broadcasters[i].localName != "broadcaster")
  4175.       continue;
  4176.  
  4177.     if (broadcasters[i] != sidebarBroadcaster)
  4178.       broadcasters[i].removeAttribute("checked");
  4179.     else
  4180.       sidebarBroadcaster.setAttribute("checked", "true");
  4181.   }
  4182.  
  4183.   sidebarBox.hidden = false;
  4184.   sidebarSplitter.hidden = false;
  4185.  
  4186.   var url = sidebarBroadcaster.getAttribute("sidebarurl");
  4187.   var title = sidebarBroadcaster.getAttribute("sidebartitle");
  4188.   if (!title)
  4189.     title = sidebarBroadcaster.getAttribute("label");
  4190.   sidebar.setAttribute("src", url); // kick off async load
  4191.   sidebarBox.setAttribute("sidebarcommand", sidebarBroadcaster.id);
  4192.   sidebarTitle.value = title;
  4193.  
  4194.   // We set this attribute here in addition to setting it on the <browser>
  4195.   // element itself, because the code in BrowserShutdown persists this
  4196.   // attribute, not the "src" of the <browser id="sidebar">. The reason it
  4197.   // does that is that we want to delay sidebar load a bit when a browser
  4198.   // window opens. See delayedStartup().
  4199.   sidebarBox.setAttribute("src", url);
  4200.  
  4201.   if (sidebar.contentDocument.location.href != url)
  4202.     sidebar.addEventListener("load", sidebarOnLoad, true);
  4203.   else // older code handled this case, so we do it too
  4204.     fireSidebarFocusedEvent();
  4205. }
  4206.  
  4207. function sidebarOnLoad(event) {
  4208.   var sidebar = document.getElementById("sidebar");
  4209.   sidebar.removeEventListener("load", sidebarOnLoad, true);
  4210.   // We're handling the 'load' event before it bubbles up to the usual
  4211.   // (non-capturing) event handlers. Let it bubble up before firing the
  4212.   // SidebarFocused event.
  4213.   setTimeout(fireSidebarFocusedEvent, 0);
  4214. }
  4215.  
  4216. /**
  4217.  * Fire a "SidebarFocused" event on the sidebar's |window| to give the sidebar
  4218.  * a chance to adjust focus as needed. An additional event is needed, because
  4219.  * we don't want to focus the sidebar when it's opened on startup or in a new
  4220.  * window, only when the user opens the sidebar.
  4221.  */
  4222. function fireSidebarFocusedEvent() {
  4223.   var sidebar = document.getElementById("sidebar");
  4224.   var event = document.createEvent("Events");
  4225.   event.initEvent("SidebarFocused", true, false);
  4226.   sidebar.contentWindow.dispatchEvent(event);
  4227. }
  4228.  
  4229. var gHomeButton = {
  4230.   prefDomain: "browser.startup.homepage",
  4231.   observe: function (aSubject, aTopic, aPrefName)
  4232.   {
  4233.     if (aTopic != "nsPref:changed" || aPrefName != this.prefDomain)
  4234.       return;
  4235.  
  4236.     this.updateTooltip();
  4237.   },
  4238.  
  4239.   updateTooltip: function (homeButton)
  4240.   {
  4241.     if (!homeButton)
  4242.       homeButton = document.getElementById("home-button");
  4243.     if (homeButton) {
  4244.       var homePage = this.getHomePage();
  4245.       homePage = homePage.replace(/\|/g,', ');
  4246.       homeButton.setAttribute("tooltiptext", homePage);
  4247.     }
  4248.   },
  4249.  
  4250.   getHomePage: function ()
  4251.   {
  4252.     var url;
  4253.     try {
  4254.       url = gPrefService.getComplexValue(this.prefDomain,
  4255.                                 Components.interfaces.nsIPrefLocalizedString).data;
  4256.     } catch (e) {
  4257.     }
  4258.  
  4259.     // use this if we can't find the pref
  4260.     if (!url) {
  4261.       var SBS = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService);
  4262.       var configBundle = SBS.createBundle("resource:/browserconfig.properties");
  4263.       url = configBundle.GetStringFromName(this.prefDomain);
  4264.     }
  4265.  
  4266.     return url;
  4267.   },
  4268.  
  4269.   updatePersonalToolbarStyle: function (homeButton)
  4270.   {
  4271.     if (!homeButton)
  4272.       homeButton = document.getElementById("home-button");
  4273.     if (homeButton)
  4274.       homeButton.className = homeButton.parentNode.id == "PersonalToolbar"
  4275.                                || homeButton.parentNode.parentNode.id == "PersonalToolbar" ?
  4276.                              homeButton.className.replace("toolbarbutton-1", "bookmark-item") :
  4277.                              homeButton.className.replace("bookmark-item", "toolbarbutton-1");
  4278.   }
  4279. };
  4280.  
  4281. /**
  4282.  * Gets the selected text in the active browser. Leading and trailing
  4283.  * whitespace is removed, and consecutive whitespace is replaced by a single
  4284.  * space. A maximum of 150 characters will be returned, regardless of the value
  4285.  * of aCharLen.
  4286.  *
  4287.  * @param aCharLen
  4288.  *        The maximum number of characters to return.
  4289.  */
  4290. function getBrowserSelection(aCharLen) {
  4291.   // selections of more than 150 characters aren't useful
  4292.   const kMaxSelectionLen = 150;
  4293.   const charLen = Math.min(aCharLen || kMaxSelectionLen, kMaxSelectionLen);
  4294.  
  4295.   var focusedWindow = document.commandDispatcher.focusedWindow;
  4296.   var selection = focusedWindow.getSelection().toString();
  4297.  
  4298.   if (selection) {
  4299.     if (selection.length > charLen) {
  4300.       // only use the first charLen important chars. see bug 221361
  4301.       var pattern = new RegExp("^(?:\\s*.){0," + charLen + "}");
  4302.       pattern.test(selection);
  4303.       selection = RegExp.lastMatch;
  4304.     }
  4305.  
  4306.     selection = selection.replace(/^\s+/, "")
  4307.                          .replace(/\s+$/, "")
  4308.                          .replace(/\s+/g, " ");
  4309.  
  4310.     if (selection.length > charLen)
  4311.       selection = selection.substr(0, charLen);
  4312.   }
  4313.   return selection;
  4314. }
  4315.  
  4316. var gWebPanelURI;
  4317. function openWebPanel(aTitle, aURI)
  4318. {
  4319.     // Ensure that the web panels sidebar is open.
  4320.     toggleSidebar('viewWebPanelsSidebar', true);
  4321.  
  4322.     // Set the title of the panel.
  4323.     document.getElementById("sidebar-title").value = aTitle;
  4324.  
  4325.     // Tell the Web Panels sidebar to load the bookmark.
  4326.     var sidebar = document.getElementById("sidebar");
  4327.     if (sidebar.docShell && sidebar.contentDocument && sidebar.contentDocument.getElementById('web-panels-browser')) {
  4328.         sidebar.contentWindow.loadWebPanel(aURI);
  4329.         if (gWebPanelURI) {
  4330.             gWebPanelURI = "";
  4331.             sidebar.removeEventListener("load", asyncOpenWebPanel, true);
  4332.         }
  4333.     }
  4334.     else {
  4335.         // The panel is still being constructed.  Attach an onload handler.
  4336.         if (!gWebPanelURI)
  4337.             sidebar.addEventListener("load", asyncOpenWebPanel, true);
  4338.         gWebPanelURI = aURI;
  4339.     }
  4340. }
  4341.  
  4342. function asyncOpenWebPanel(event)
  4343. {
  4344.     var sidebar = document.getElementById("sidebar");
  4345.     if (gWebPanelURI && sidebar.contentDocument && sidebar.contentDocument.getElementById('web-panels-browser'))
  4346.         sidebar.contentWindow.loadWebPanel(gWebPanelURI);
  4347.     gWebPanelURI = "";
  4348.     sidebar.removeEventListener("load", asyncOpenWebPanel, true);
  4349. }
  4350.  
  4351. /*
  4352.  * - [ Dependencies ] ---------------------------------------------------------
  4353.  *  utilityOverlay.js:
  4354.  *    - gatherTextUnder
  4355.  */
  4356.  
  4357.  // Called whenever the user clicks in the content area,
  4358.  // except when left-clicking on links (special case)
  4359.  // should always return true for click to go through
  4360.  function contentAreaClick(event, fieldNormalClicks)
  4361.  {
  4362.    if (!event.isTrusted || event.getPreventDefault()) {
  4363.      return true;
  4364.    }
  4365.  
  4366.    var target = event.target;
  4367.    var linkNode;
  4368.  
  4369.    if (target instanceof HTMLAnchorElement ||
  4370.        target instanceof HTMLAreaElement ||
  4371.        target instanceof HTMLLinkElement) {
  4372.      if (target.hasAttribute("href"))
  4373.        linkNode = target;
  4374.  
  4375.      // xxxmpc: this is kind of a hack to work around a Gecko bug (see bug 266932)
  4376.      // we're going to walk up the DOM looking for a parent link node,
  4377.      // this shouldn't be necessary, but we're matching the existing behaviour for left click
  4378.      var parent = target.parentNode;
  4379.      while (parent) {
  4380.        if (parent instanceof HTMLAnchorElement ||
  4381.            parent instanceof HTMLAreaElement ||
  4382.            parent instanceof HTMLLinkElement) {
  4383.            if (parent.hasAttribute("href"))
  4384.              linkNode = parent;
  4385.        }
  4386.        parent = parent.parentNode;
  4387.      }
  4388.    }
  4389.    else {
  4390.      linkNode = event.originalTarget;
  4391.      while (linkNode && !(linkNode instanceof HTMLAnchorElement))
  4392.        linkNode = linkNode.parentNode;
  4393.      // <a> cannot be nested.  So if we find an anchor without an
  4394.      // href, there is no useful <a> around the target
  4395.      if (linkNode && !linkNode.hasAttribute("href"))
  4396.        linkNode = null;
  4397.    }
  4398.    var wrapper = null;
  4399.    if (linkNode) {
  4400.      wrapper = linkNode;
  4401.      if (event.button == 0 && !event.ctrlKey && !event.shiftKey &&
  4402.          !event.altKey && !event.metaKey) {
  4403.        // A Web panel's links should target the main content area.  Do this
  4404.        // if no modifier keys are down and if there's no target or the target equals
  4405.        // _main (the IE convention) or _content (the Mozilla convention).
  4406.        // XXX Now that markLinkVisited is gone, we may not need to field _main and
  4407.        // _content here.
  4408.        target = wrapper.getAttribute("target");
  4409.        if (fieldNormalClicks &&
  4410.            (!target || target == "_content" || target  == "_main"))
  4411.          // IE uses _main, SeaMonkey uses _content, we support both
  4412.        {
  4413.          if (!wrapper.href)
  4414.            return true;
  4415.          if (wrapper.getAttribute("onclick"))
  4416.            return true;
  4417.          // javascript links should be executed in the current browser
  4418.          if (wrapper.href.substr(0, 11) === "javascript:")
  4419.            return true;
  4420.          // data links should be executed in the current browser
  4421.          if (wrapper.href.substr(0, 5) === "data:")
  4422.            return true;
  4423.  
  4424.          try {
  4425.            urlSecurityCheck(wrapper.href, wrapper.ownerDocument.nodePrincipal);
  4426.          }
  4427.          catch(ex) {
  4428.            return false;
  4429.          } 
  4430.  
  4431.          var postData = { };
  4432.          var url = getShortcutOrURI(wrapper.href, postData);
  4433.          if (!url)
  4434.            return true;
  4435.          loadURI(url, null, postData.value, false);
  4436.          event.preventDefault();
  4437.          return false;
  4438.        }
  4439.        else if (linkNode.getAttribute("rel") == "sidebar") {
  4440.          // This is the Opera convention for a special link that - when clicked - allows
  4441.          // you to add a sidebar panel.  We support the Opera convention here.  The link's
  4442.          // title attribute contains the title that should be used for the sidebar panel.
  4443.          PlacesUIUtils.showMinimalAddBookmarkUI(makeURI(wrapper.href),
  4444.                                                 wrapper.getAttribute("title"),
  4445.                                                 null, null, true, true);
  4446.          event.preventDefault();
  4447.          return false;
  4448.        }
  4449.      }
  4450.      else {
  4451.        handleLinkClick(event, wrapper.href, linkNode);
  4452.      }
  4453.  
  4454.      return true;
  4455.    } else {
  4456.      // Try simple XLink
  4457.      var href, realHref, baseURI;
  4458.      linkNode = target;
  4459.      while (linkNode) {
  4460.        if (linkNode.nodeType == Node.ELEMENT_NODE) {
  4461.          wrapper = linkNode;
  4462.  
  4463.          realHref = wrapper.getAttributeNS("http://www.w3.org/1999/xlink", "href");
  4464.          if (realHref) {
  4465.            href = realHref;
  4466.            baseURI = wrapper.baseURI
  4467.          }
  4468.        }
  4469.        linkNode = linkNode.parentNode;
  4470.      }
  4471.      if (href) {
  4472.        href = makeURLAbsolute(baseURI, href);
  4473.        handleLinkClick(event, href, null);
  4474.        return true;
  4475.      }
  4476.    }
  4477.    if (event.button == 1 &&
  4478.        gPrefService.getBoolPref("middlemouse.contentLoadURL") &&
  4479.        !gPrefService.getBoolPref("general.autoScroll")) {
  4480.      middleMousePaste(event);
  4481.    }
  4482.    return true;
  4483.  }
  4484.  
  4485. function handleLinkClick(event, href, linkNode)
  4486. {
  4487.   var doc = event.target.ownerDocument;
  4488.  
  4489.   switch (event.button) {
  4490.     case 0:    // if left button clicked
  4491. //@line 4886 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  4492.       if (event.ctrlKey) {
  4493. //@line 4888 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  4494.         openNewTabWith(href, doc, null, event, false);
  4495.         event.stopPropagation();
  4496.         return true;
  4497.       }
  4498.  
  4499.       if (event.shiftKey && event.altKey) {
  4500.         var feedService = 
  4501.             Cc["@mozilla.org/browser/feeds/result-service;1"].
  4502.             getService(Ci.nsIFeedResultService);
  4503.         feedService.forcePreviewPage = true;
  4504.         loadURI(href, null, null, false);
  4505.         return false;
  4506.       }
  4507.                                                        
  4508.       if (event.shiftKey) {
  4509.         openNewWindowWith(href, doc, null, false);
  4510.         event.stopPropagation();
  4511.         return true;
  4512.       }
  4513.  
  4514.       if (event.altKey) {
  4515.         saveURL(href, linkNode ? gatherTextUnder(linkNode) : "", null, true,
  4516.                 true, doc.documentURIObject);
  4517.         return true;
  4518.       }
  4519.  
  4520.       return false;
  4521.     case 1:    // if middle button clicked
  4522.       var tab;
  4523.       try {
  4524.         tab = gPrefService.getBoolPref("browser.tabs.opentabfor.middleclick")
  4525.       }
  4526.       catch(ex) {
  4527.         tab = true;
  4528.       }
  4529.       if (tab)
  4530.         openNewTabWith(href, doc, null, event, false);
  4531.       else
  4532.         openNewWindowWith(href, doc, null, false);
  4533.       event.stopPropagation();
  4534.       return true;
  4535.   }
  4536.   return false;
  4537. }
  4538.  
  4539. function middleMousePaste(event)
  4540. {
  4541.   var url = readFromClipboard();
  4542.   if (!url)
  4543.     return;
  4544.   var postData = { };
  4545.   url = getShortcutOrURI(url, postData);
  4546.   if (!url)
  4547.     return;
  4548.  
  4549.   try {
  4550.     addToUrlbarHistory(url);
  4551.   } catch (ex) {
  4552.     // Things may go wrong when adding url to session history,
  4553.     // but don't let that interfere with the loading of the url.
  4554.   }
  4555.  
  4556.   openUILink(url,
  4557.              event,
  4558.              true /* ignore the fact this is a middle click */);
  4559.  
  4560.   event.stopPropagation();
  4561. }
  4562.  
  4563. /*
  4564.  * Note that most of this routine has been moved into C++ in order to
  4565.  * be available for all <browser> tags as well as gecko embedding. See
  4566.  * mozilla/content/base/src/nsContentAreaDragDrop.cpp.
  4567.  *
  4568.  * Do not add any new fuctionality here other than what is needed for
  4569.  * a standalone product.
  4570.  */
  4571.  
  4572. var contentAreaDNDObserver = {
  4573.   onDrop: function (aEvent, aXferData, aDragSession)
  4574.     {
  4575.       var url = transferUtils.retrieveURLFromData(aXferData.data, aXferData.flavour.contentType);
  4576.  
  4577.       // valid urls don't contain spaces ' '; if we have a space it
  4578.       // isn't a valid url, or if it's a javascript: or data: url,
  4579.       // bail out
  4580.       if (!url || !url.length || url.indexOf(" ", 0) != -1 ||
  4581.           /^\s*(javascript|data):/.test(url))
  4582.         return;
  4583.  
  4584.       nsDragAndDrop.dragDropSecurityCheck(aEvent, aDragSession, url);
  4585.  
  4586.       switch (document.documentElement.getAttribute('windowtype')) {
  4587.         case "navigator:browser":
  4588.           var postData = { };
  4589.           var uri = getShortcutOrURI(url, postData);
  4590.           loadURI(uri, null, postData.value, false);
  4591.           break;
  4592.         case "navigator:view-source":
  4593.           viewSource(url);
  4594.           break;
  4595.       }
  4596.  
  4597.       // keep the event from being handled by the dragDrop listeners
  4598.       // built-in to gecko if they happen to be above us.
  4599.       aEvent.preventDefault();
  4600.     },
  4601.  
  4602.   getSupportedFlavours: function ()
  4603.     {
  4604.       var flavourSet = new FlavourSet();
  4605.       flavourSet.appendFlavour("text/x-moz-url");
  4606.       flavourSet.appendFlavour("text/unicode");
  4607.       flavourSet.appendFlavour("application/x-moz-file", "nsIFile");
  4608.       return flavourSet;
  4609.     }
  4610.  
  4611. };
  4612.  
  4613. function getBrowser()
  4614. {
  4615.   if (!gBrowser)
  4616.     gBrowser = document.getElementById("content");
  4617.   return gBrowser;
  4618. }
  4619.  
  4620. function getNavToolbox()
  4621. {
  4622.   if (!gNavToolbox)
  4623.     gNavToolbox = document.getElementById("navigator-toolbox");
  4624.   return gNavToolbox;
  4625. }
  4626.  
  4627. function MultiplexHandler(event)
  4628. { try {
  4629.     var node = event.target;
  4630.     var name = node.getAttribute('name');
  4631.  
  4632.     if (name == 'detectorGroup') {
  4633.         SetForcedDetector(true);
  4634.         SelectDetector(event, false);
  4635.     } else if (name == 'charsetGroup') {
  4636.         var charset = node.getAttribute('id');
  4637.         charset = charset.substring('charset.'.length, charset.length)
  4638.         SetForcedCharset(charset);
  4639.     } else if (name == 'charsetCustomize') {
  4640.         //do nothing - please remove this else statement, once the charset prefs moves to the pref window
  4641.     } else {
  4642.         SetForcedCharset(node.getAttribute('id'));
  4643.     }
  4644.     } catch(ex) { alert(ex); }
  4645. }
  4646.  
  4647. function SelectDetector(event, doReload)
  4648. {
  4649.     var uri =  event.target.getAttribute("id");
  4650.     var prefvalue = uri.substring('chardet.'.length, uri.length);
  4651.     if ("off" == prefvalue) { // "off" is special value to turn off the detectors
  4652.         prefvalue = "";
  4653.     }
  4654.  
  4655.     try {
  4656.         var pref = Components.classes["@mozilla.org/preferences-service;1"]
  4657.                              .getService(Components.interfaces.nsIPrefBranch);
  4658.         var str =  Components.classes["@mozilla.org/supports-string;1"]
  4659.                              .createInstance(Components.interfaces.nsISupportsString);
  4660.  
  4661.         str.data = prefvalue;
  4662.         pref.setComplexValue("intl.charset.detector",
  4663.                              Components.interfaces.nsISupportsString, str);
  4664.         if (doReload) window.content.location.reload();
  4665.     }
  4666.     catch (ex) {
  4667.         dump("Failed to set the intl.charset.detector preference.\n");
  4668.     }
  4669. }
  4670.  
  4671. function SetForcedDetector(doReload)
  4672. {
  4673.     BrowserSetForcedDetector(doReload);
  4674. }
  4675.  
  4676. function SetForcedCharset(charset)
  4677. {
  4678.     BrowserSetForcedCharacterSet(charset);
  4679. }
  4680.  
  4681. function BrowserSetForcedCharacterSet(aCharset)
  4682. {
  4683.   var docCharset = getBrowser().docShell.QueryInterface(
  4684.                             Components.interfaces.nsIDocCharset);
  4685.   docCharset.charset = aCharset;
  4686.   // Save the forced character-set
  4687.   PlacesUtils.history.setCharsetForURI(getWebNavigation().currentURI, aCharset);
  4688.   BrowserReloadWithFlags(nsIWebNavigation.LOAD_FLAGS_CHARSET_CHANGE);
  4689. }
  4690.  
  4691. function BrowserSetForcedDetector(doReload)
  4692. {
  4693.   getBrowser().documentCharsetInfo.forcedDetector = true;
  4694.   if (doReload)
  4695.     BrowserReloadWithFlags(nsIWebNavigation.LOAD_FLAGS_CHARSET_CHANGE);
  4696. }
  4697.  
  4698. function UpdateCurrentCharset()
  4699. {
  4700.     // extract the charset from DOM
  4701.     var wnd = document.commandDispatcher.focusedWindow;
  4702.     if ((window == wnd) || (wnd == null)) wnd = window.content;
  4703.  
  4704.     // Uncheck previous item
  4705.     if (gPrevCharset) {
  4706.         var pref_item = document.getElementById('charset.' + gPrevCharset);
  4707.         if (pref_item)
  4708.           pref_item.setAttribute('checked', 'false');
  4709.     }
  4710.  
  4711.     var menuitem = document.getElementById('charset.' + wnd.document.characterSet);
  4712.     if (menuitem) {
  4713.         menuitem.setAttribute('checked', 'true');
  4714.     }
  4715. }
  4716.  
  4717. function UpdateCharsetDetector()
  4718. {
  4719.     var prefvalue;
  4720.  
  4721.     try {
  4722.         var pref = Components.classes["@mozilla.org/preferences-service;1"]
  4723.                              .getService(Components.interfaces.nsIPrefBranch);
  4724.         prefvalue = pref.getComplexValue("intl.charset.detector",
  4725.                                          Components.interfaces.nsIPrefLocalizedString).data;
  4726.     }
  4727.     catch (ex) {
  4728.         prefvalue = "";
  4729.     }
  4730.  
  4731.     if (prefvalue == "") prefvalue = "off";
  4732.     dump("intl.charset.detector = "+ prefvalue + "\n");
  4733.  
  4734.     prefvalue = 'chardet.' + prefvalue;
  4735.     var menuitem = document.getElementById(prefvalue);
  4736.  
  4737.     if (menuitem) {
  4738.         menuitem.setAttribute('checked', 'true');
  4739.     }
  4740. }
  4741.  
  4742. function UpdateMenus(event)
  4743. {
  4744.     // use setTimeout workaround to delay checkmark the menu
  4745.     // when onmenucomplete is ready then use it instead of oncreate
  4746.     // see bug 78290 for the detail
  4747.     UpdateCurrentCharset();
  4748.     setTimeout(UpdateCurrentCharset, 0);
  4749.     UpdateCharsetDetector();
  4750.     setTimeout(UpdateCharsetDetector, 0);
  4751. }
  4752.  
  4753. function CreateMenu(node)
  4754. {
  4755.   var observerService = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  4756.   observerService.notifyObservers(null, "charsetmenu-selected", node);
  4757. }
  4758.  
  4759. function charsetLoadListener (event)
  4760. {
  4761.     var charset = window.content.document.characterSet;
  4762.  
  4763.     if (charset.length > 0 && (charset != gLastBrowserCharset)) {
  4764.         if (!gCharsetMenu)
  4765.           gCharsetMenu = Components.classes['@mozilla.org/rdf/datasource;1?name=charset-menu'].getService().QueryInterface(Components.interfaces.nsICurrentCharsetListener);
  4766.         gCharsetMenu.SetCurrentCharset(charset);
  4767.         gPrevCharset = gLastBrowserCharset;
  4768.         gLastBrowserCharset = charset;
  4769.     }
  4770. }
  4771.  
  4772. /* Begin Page Style Functions */
  4773. function getStyleSheetArray(frame)
  4774. {
  4775.   var styleSheets = frame.document.styleSheets;
  4776.   var styleSheetsArray = new Array(styleSheets.length);
  4777.   for (var i = 0; i < styleSheets.length; i++) {
  4778.     styleSheetsArray[i] = styleSheets[i];
  4779.   }
  4780.   return styleSheetsArray;
  4781. }
  4782.  
  4783. function getAllStyleSheets(frameset)
  4784. {
  4785.   var styleSheetsArray = getStyleSheetArray(frameset);
  4786.   for (var i = 0; i < frameset.frames.length; i++) {
  4787.     var frameSheets = getAllStyleSheets(frameset.frames[i]);
  4788.     styleSheetsArray = styleSheetsArray.concat(frameSheets);
  4789.   }
  4790.   return styleSheetsArray;
  4791. }
  4792.  
  4793. function stylesheetFillPopup(menuPopup)
  4794. {
  4795.   var noStyle = menuPopup.firstChild;
  4796.   var persistentOnly = noStyle.nextSibling;
  4797.   var sep = persistentOnly.nextSibling;
  4798.   while (sep.nextSibling)
  4799.     menuPopup.removeChild(sep.nextSibling);
  4800.  
  4801.   var styleSheets = getAllStyleSheets(window.content);
  4802.   var currentStyleSheets = [];
  4803.   var styleDisabled = getMarkupDocumentViewer().authorStyleDisabled;
  4804.   var haveAltSheets = false;
  4805.   var altStyleSelected = false;
  4806.  
  4807.   for (var i = 0; i < styleSheets.length; ++i) {
  4808.     var currentStyleSheet = styleSheets[i];
  4809.  
  4810.     // Skip any stylesheets that don't match the screen media type.
  4811.     var media = currentStyleSheet.media.mediaText.toLowerCase();
  4812.     if (media && (media.indexOf("screen") == -1) && (media.indexOf("all") == -1))
  4813.         continue;
  4814.  
  4815.     if (currentStyleSheet.title) {
  4816.       if (!currentStyleSheet.disabled)
  4817.         altStyleSelected = true;
  4818.  
  4819.       haveAltSheets = true;
  4820.  
  4821.       var lastWithSameTitle = null;
  4822.       if (currentStyleSheet.title in currentStyleSheets)
  4823.         lastWithSameTitle = currentStyleSheets[currentStyleSheet.title];
  4824.  
  4825.       if (!lastWithSameTitle) {
  4826.         var menuItem = document.createElement("menuitem");
  4827.         menuItem.setAttribute("type", "radio");
  4828.         menuItem.setAttribute("label", currentStyleSheet.title);
  4829.         menuItem.setAttribute("data", currentStyleSheet.title);
  4830.         menuItem.setAttribute("checked", !currentStyleSheet.disabled && !styleDisabled);
  4831.         menuPopup.appendChild(menuItem);
  4832.         currentStyleSheets[currentStyleSheet.title] = menuItem;
  4833.       } else {
  4834.         if (currentStyleSheet.disabled)
  4835.           lastWithSameTitle.removeAttribute("checked");
  4836.       }
  4837.     }
  4838.   }
  4839.  
  4840.   noStyle.setAttribute("checked", styleDisabled);
  4841.   persistentOnly.setAttribute("checked", !altStyleSelected && !styleDisabled);
  4842.   persistentOnly.hidden = (window.content.document.preferredStyleSheetSet) ? haveAltSheets : false;
  4843.   sep.hidden = (noStyle.hidden && persistentOnly.hidden) || !haveAltSheets;
  4844.   return true;
  4845. }
  4846.  
  4847. function stylesheetInFrame(frame, title) {
  4848.   var docStyleSheets = frame.document.styleSheets;
  4849.  
  4850.   for (var i = 0; i < docStyleSheets.length; ++i) {
  4851.     if (docStyleSheets[i].title == title)
  4852.       return true;
  4853.   }
  4854.   return false;
  4855. }
  4856.  
  4857. function stylesheetSwitchFrame(frame, title) {
  4858.   var docStyleSheets = frame.document.styleSheets;
  4859.  
  4860.   for (var i = 0; i < docStyleSheets.length; ++i) {
  4861.     var docStyleSheet = docStyleSheets[i];
  4862.  
  4863.     if (title == "_nostyle")
  4864.       docStyleSheet.disabled = true;
  4865.     else if (docStyleSheet.title)
  4866.       docStyleSheet.disabled = (docStyleSheet.title != title);
  4867.     else if (docStyleSheet.disabled)
  4868.       docStyleSheet.disabled = false;
  4869.   }
  4870. }
  4871.  
  4872. function stylesheetSwitchAll(frameset, title) {
  4873.   if (!title || title == "_nostyle" || stylesheetInFrame(frameset, title)) {
  4874.     stylesheetSwitchFrame(frameset, title);
  4875.   }
  4876.   for (var i = 0; i < frameset.frames.length; i++) {
  4877.     stylesheetSwitchAll(frameset.frames[i], title);
  4878.   }
  4879. }
  4880.  
  4881. function setStyleDisabled(disabled) {
  4882.   getMarkupDocumentViewer().authorStyleDisabled = disabled;
  4883. }
  4884.  
  4885. /* End of the Page Style functions */
  4886.  
  4887. var BrowserOffline = {
  4888.   /////////////////////////////////////////////////////////////////////////////
  4889.   // BrowserOffline Public Methods
  4890.   init: function ()
  4891.   {
  4892.     if (!this._uiElement)
  4893.       this._uiElement = document.getElementById("goOfflineMenuitem");
  4894.  
  4895.     var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  4896.     os.addObserver(this, "network:offline-status-changed", false);
  4897.  
  4898.     var ioService = Components.classes["@mozilla.org/network/io-service;1"].
  4899.       getService(Components.interfaces.nsIIOService2);
  4900.  
  4901.     // if ioService is managing the offline status, then ioservice.offline
  4902.     // is already set correctly. We will continue to allow the ioService
  4903.     // to manage its offline state until the user uses the "Work Offline" UI.
  4904.     
  4905.     if (!ioService.manageOfflineStatus) {
  4906.       // set the initial state
  4907.       var isOffline = false;
  4908.       try {
  4909.         isOffline = gPrefService.getBoolPref("browser.offline");
  4910.       }
  4911.       catch (e) { }
  4912.       ioService.offline = isOffline;
  4913.     }
  4914.     
  4915.     this._updateOfflineUI(ioService.offline);
  4916.   },
  4917.  
  4918.   uninit: function ()
  4919.   {
  4920.     try {
  4921.       var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  4922.       os.removeObserver(this, "network:offline-status-changed");
  4923.     } catch (ex) {
  4924.     }
  4925.   },
  4926.  
  4927.   toggleOfflineStatus: function ()
  4928.   {
  4929.     var ioService = Components.classes["@mozilla.org/network/io-service;1"].
  4930.       getService(Components.interfaces.nsIIOService2);
  4931.  
  4932.     // Stop automatic management of the offline status
  4933.     try {
  4934.       ioService.manageOfflineStatus = false;
  4935.     } catch (ex) {
  4936.     }
  4937.   
  4938.     if (!ioService.offline && !this._canGoOffline()) {
  4939.       this._updateOfflineUI(false);
  4940.       return;
  4941.     }
  4942.  
  4943.     ioService.offline = !ioService.offline;
  4944.  
  4945.     // Save the current state for later use as the initial state
  4946.     // (if there is no netLinkService)
  4947.     gPrefService.setBoolPref("browser.offline", ioService.offline);
  4948.   },
  4949.  
  4950.   /////////////////////////////////////////////////////////////////////////////
  4951.   // nsIObserver
  4952.   observe: function (aSubject, aTopic, aState)
  4953.   {
  4954.     if (aTopic != "network:offline-status-changed")
  4955.       return;
  4956.  
  4957.     this._updateOfflineUI(aState == "offline");
  4958.   },
  4959.  
  4960.   /////////////////////////////////////////////////////////////////////////////
  4961.   // BrowserOffline Implementation Methods
  4962.   _canGoOffline: function ()
  4963.   {
  4964.     var os = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
  4965.     if (os) {
  4966.       try {
  4967.         var cancelGoOffline = Components.classes["@mozilla.org/supports-PRBool;1"].createInstance(Components.interfaces.nsISupportsPRBool);
  4968.         os.notifyObservers(cancelGoOffline, "offline-requested", null);
  4969.  
  4970.         // Something aborted the quit process.
  4971.         if (cancelGoOffline.data)
  4972.           return false;
  4973.       }
  4974.       catch (ex) {
  4975.       }
  4976.     }
  4977.     return true;
  4978.   },
  4979.  
  4980.   _uiElement: null,
  4981.   _updateOfflineUI: function (aOffline)
  4982.   {
  4983.     var offlineLocked = gPrefService.prefIsLocked("network.online");
  4984.     if (offlineLocked)
  4985.       this._uiElement.setAttribute("disabled", "true");
  4986.  
  4987.     this._uiElement.setAttribute("checked", aOffline);
  4988.   }
  4989. };
  4990.  
  4991. var OfflineApps = {
  4992.   /////////////////////////////////////////////////////////////////////////////
  4993.   // OfflineApps Public Methods
  4994.   init: function ()
  4995.   {
  4996.     var obs = Cc["@mozilla.org/observer-service;1"].
  4997.               getService(Ci.nsIObserverService);
  4998.     obs.addObserver(this, "dom-storage-warn-quota-exceeded", false);
  4999.     obs.addObserver(this, "offline-cache-update-completed", false);
  5000.   },
  5001.  
  5002.   uninit: function ()
  5003.   {
  5004.     var obs = Cc["@mozilla.org/observer-service;1"].
  5005.               getService(Ci.nsIObserverService);
  5006.     obs.removeObserver(this, "dom-storage-warn-quota-exceeded");
  5007.     obs.removeObserver(this, "offline-cache-update-completed");
  5008.   },
  5009.  
  5010.   /////////////////////////////////////////////////////////////////////////////
  5011.   // OfflineApps Implementation Methods
  5012.  
  5013.   // XXX: _getBrowserWindowForContentWindow and _getBrowserForContentWindow
  5014.   // were taken from browser/components/feeds/src/WebContentConverter.
  5015.   _getBrowserWindowForContentWindow: function(aContentWindow) {
  5016.     return aContentWindow.QueryInterface(Ci.nsIInterfaceRequestor)
  5017.                          .getInterface(Ci.nsIWebNavigation)
  5018.                          .QueryInterface(Ci.nsIDocShellTreeItem)
  5019.                          .rootTreeItem
  5020.                          .QueryInterface(Ci.nsIInterfaceRequestor)
  5021.                          .getInterface(Ci.nsIDOMWindow)
  5022.                          .wrappedJSObject;
  5023.   },
  5024.  
  5025.   _getBrowserForContentWindow: function(aBrowserWindow, aContentWindow) {
  5026.     // This depends on pseudo APIs of browser.js and tabbrowser.xml
  5027.     aContentWindow = aContentWindow.top;
  5028.     var browsers = aBrowserWindow.getBrowser().browsers;
  5029.     for (var i = 0; i < browsers.length; ++i) {
  5030.       if (browsers[i].contentWindow == aContentWindow)
  5031.         return browsers[i];
  5032.     }
  5033.   },
  5034.  
  5035.   _getManifestURI: function(aWindow) {
  5036.     var attr = aWindow.document.documentElement.getAttribute("manifest");
  5037.     if (!attr) return null;
  5038.  
  5039.     try {
  5040.       var ios = Cc["@mozilla.org/network/io-service;1"].
  5041.                 getService(Ci.nsIIOService);
  5042.  
  5043.       var contentURI = ios.newURI(aWindow.location.href, null, null);
  5044.       return ios.newURI(attr, aWindow.document.characterSet, contentURI);
  5045.     } catch (e) {
  5046.       return null;
  5047.     }
  5048.   },
  5049.  
  5050.   // A cache update isn't tied to a specific window.  Try to find
  5051.   // the best browser in which to warn the user about space usage
  5052.   _getBrowserForCacheUpdate: function(aCacheUpdate) {
  5053.     // Prefer the current browser
  5054.     var uri = this._getManifestURI(gBrowser.mCurrentBrowser.contentWindow);
  5055.     if (uri && uri.equals(aCacheUpdate.manifestURI)) {
  5056.       return gBrowser.mCurrentBrowser;
  5057.     }
  5058.  
  5059.     var browsers = getBrowser().browsers;
  5060.     for (var i = 0; i < browsers.length; ++i) {
  5061.       uri = this._getManifestURI(browsers[i].contentWindow);
  5062.       if (uri && uri.equals(aCacheUpdate.manifestURI)) {
  5063.         return browsers[i];
  5064.       }
  5065.     }
  5066.  
  5067.     return null;
  5068.   },
  5069.  
  5070.   _warnUsage: function(aBrowser, aURI) {
  5071.     if (!aBrowser)
  5072.       return;
  5073.  
  5074.     var notificationBox = gBrowser.getNotificationBox(aBrowser);
  5075.     var notification = notificationBox.getNotificationWithValue("offline-app-usage");
  5076.     if (!notification) {
  5077.       var bundle_browser = document.getElementById("bundle_browser");
  5078.  
  5079.       var buttons = [{
  5080.           label: bundle_browser.getString("offlineApps.manageUsage"),
  5081.           accessKey: bundle_browser.getString("offlineApps.manageUsageAccessKey"),
  5082.           callback: OfflineApps.manage
  5083.         }];
  5084.  
  5085.       var warnQuota = gPrefService.getIntPref("offline-apps.quota.warn");
  5086.       const priority = notificationBox.PRIORITY_WARNING_MEDIUM;
  5087.       var message = bundle_browser.getFormattedString("offlineApps.usage",
  5088.                                                       [ aURI.host,
  5089.                                                         warnQuota / 1024 ]);
  5090.  
  5091.       notificationBox.appendNotification(message, "offline-app-usage",
  5092.                                          "chrome://browser/skin/Info.png",
  5093.                                          priority, buttons);
  5094.     }
  5095.  
  5096.     // Now that we've warned once, prevent the warning from showing up
  5097.     // again.
  5098.     var pm = Cc["@mozilla.org/permissionmanager;1"].
  5099.              getService(Ci.nsIPermissionManager);
  5100.     pm.add(aURI, "offline-app",
  5101.            Ci.nsIOfflineCacheUpdateService.ALLOW_NO_WARN);
  5102.   },
  5103.  
  5104.   // XXX: duplicated in preferences/advanced.js
  5105.   _getOfflineAppUsage: function (host)
  5106.   {
  5107.     var cacheService = Components.classes["@mozilla.org/network/cache-service;1"].
  5108.                        getService(Components.interfaces.nsICacheService);
  5109.     var cacheSession = cacheService.createSession("HTTP-offline",
  5110.                                                   Components.interfaces.nsICache.STORE_OFFLINE,
  5111.                                                   true).
  5112.                        QueryInterface(Components.interfaces.nsIOfflineCacheSession);
  5113.     var usage = cacheSession.getDomainUsage(host);
  5114.  
  5115.     var storageManager = Components.classes["@mozilla.org/dom/storagemanager;1"].
  5116.                          getService(Components.interfaces.nsIDOMStorageManager);
  5117.     usage += storageManager.getUsage(host);
  5118.  
  5119.     return usage;
  5120.   },
  5121.  
  5122.   _checkUsage: function(aURI) {
  5123.     var pm = Cc["@mozilla.org/permissionmanager;1"].
  5124.              getService(Ci.nsIPermissionManager);
  5125.  
  5126.     // if the user has already allowed excessive usage, don't bother checking
  5127.     if (pm.testExactPermission(aURI, "offline-app") !=
  5128.         Ci.nsIOfflineCacheUpdateService.ALLOW_NO_WARN) {
  5129.       var usage = this._getOfflineAppUsage(aURI.asciiHost);
  5130.       var warnQuota = gPrefService.getIntPref("offline-apps.quota.warn");
  5131.       if (usage >= warnQuota * 1024) {
  5132.         return true;
  5133.       }
  5134.     }
  5135.  
  5136.     return false;
  5137.   },
  5138.  
  5139.   offlineAppRequested: function(aContentWindow) {
  5140.     if (!gPrefService.getBoolPref("browser.offline-apps.notify")) {
  5141.       return;
  5142.     }
  5143.  
  5144.     var browserWindow = this._getBrowserWindowForContentWindow(aContentWindow);
  5145.     var browser = this._getBrowserForContentWindow(browserWindow,
  5146.                                                    aContentWindow);
  5147.  
  5148.     var currentURI = browser.webNavigation.currentURI;
  5149.     var pm = Cc["@mozilla.org/permissionmanager;1"].
  5150.              getService(Ci.nsIPermissionManager);
  5151.  
  5152.     // don't bother showing UI if the user has already made a decision
  5153.     if (pm.testExactPermission(currentURI, "offline-app") !=
  5154.         Ci.nsIPermissionManager.UNKNOWN_ACTION)
  5155.       return;
  5156.  
  5157.     try {
  5158.       if (gPrefService.getBoolPref("offline-apps.allow_by_default")) {
  5159.         // all pages can use offline capabilities, no need to ask the user
  5160.         return;
  5161.       }
  5162.     } catch(e) {
  5163.       // this pref isn't set by default, ignore failures
  5164.     }
  5165.  
  5166.     var notificationBox = gBrowser.getNotificationBox(browser);
  5167.     var notification = notificationBox.getNotificationWithValue("offline-app-requested");
  5168.     if (!notification) {
  5169.       var bundle_browser = document.getElementById("bundle_browser");
  5170.  
  5171.       var buttons = [{
  5172.         label: bundle_browser.getString("offlineApps.allow"),
  5173.         accessKey: bundle_browser.getString("offlineApps.allowAccessKey"),
  5174.         callback: function() { OfflineApps.allowSite(); }
  5175.       },{
  5176.         label: bundle_browser.getString("offlineApps.never"),
  5177.         accessKey: bundle_browser.getString("offlineApps.neverAccessKey"),
  5178.         callback: function() { OfflineApps.disallowSite(); }
  5179.       },{
  5180.         label: bundle_browser.getString("offlineApps.notNow"),
  5181.         accessKey: bundle_browser.getString("offlineApps.notNowAccessKey"),
  5182.         callback: function() { /* noop */ }
  5183.       }];
  5184.  
  5185.       const priority = notificationBox.PRIORITY_INFO_LOW;
  5186.       var message = bundle_browser.getFormattedString("offlineApps.available",
  5187.                                                       [ currentURI.host ]);
  5188.       notificationBox.appendNotification(message, "offline-app-requested",
  5189.                                          "chrome://browser/skin/Info.png",
  5190.                                          priority, buttons);
  5191.     }
  5192.   },
  5193.  
  5194.   allowSite: function() {
  5195.     var currentURI = gBrowser.selectedBrowser.webNavigation.currentURI;
  5196.     var pm = Cc["@mozilla.org/permissionmanager;1"].
  5197.              getService(Ci.nsIPermissionManager);
  5198.     pm.add(currentURI, "offline-app", Ci.nsIPermissionManager.ALLOW_ACTION);
  5199.  
  5200.     // When a site is enabled while loading, <link rel="offline-resource">
  5201.     // resources will start fetching immediately.  This one time we need to
  5202.     // do it ourselves.
  5203.     this._startFetching();
  5204.   },
  5205.  
  5206.   disallowSite: function() {
  5207.     var currentURI = gBrowser.selectedBrowser.webNavigation.currentURI;
  5208.     var pm = Cc["@mozilla.org/permissionmanager;1"].
  5209.              getService(Ci.nsIPermissionManager);
  5210.     pm.add(currentURI, "offline-app", Ci.nsIPermissionManager.DENY_ACTION);
  5211.   },
  5212.  
  5213.   manage: function() {
  5214.     openAdvancedPreferences("networkTab");
  5215.   },
  5216.  
  5217.   _startFetching: function() {
  5218.     var manifest = content.document.documentElement.getAttribute("manifest");
  5219.     if (!manifest)
  5220.       return;
  5221.  
  5222.     var ios = Cc["@mozilla.org/network/io-service;1"].
  5223.               getService(Ci.nsIIOService);
  5224.  
  5225.     var contentURI = ios.newURI(content.location.href, null, null);
  5226.     var manifestURI = ios.newURI(manifest, content.document.characterSet,
  5227.                                  contentURI);
  5228.  
  5229.     var updateService = Cc["@mozilla.org/offlinecacheupdate-service;1"].
  5230.                         getService(Ci.nsIOfflineCacheUpdateService);
  5231.     updateService.scheduleUpdate(manifestURI, contentURI);
  5232.   },
  5233.  
  5234.   /////////////////////////////////////////////////////////////////////////////
  5235.   // nsIObserver
  5236.   observe: function (aSubject, aTopic, aState)
  5237.   {
  5238.     if (aTopic == "dom-storage-warn-quota-exceeded") {
  5239.       if (aSubject) {
  5240.         var uri = Cc["@mozilla.org/network/io-service;1"].
  5241.                   getService(Ci.nsIIOService).
  5242.                   newURI(aSubject.location.href, null, null);
  5243.  
  5244.         if (OfflineApps._checkUsage(uri)) {
  5245.           var browserWindow =
  5246.             this._getBrowserWindowForContentWindow(aSubject);
  5247.           var browser = this._getBrowserForContentWindow(browserWindow,
  5248.                                                          aSubject);
  5249.           OfflineApps._warnUsage(browser, uri);
  5250.         }
  5251.       }
  5252.     } else if (aTopic == "offline-cache-update-completed") {
  5253.       var cacheUpdate = aSubject.QueryInterface(Ci.nsIOfflineCacheUpdate);
  5254.  
  5255.       var uri = cacheUpdate.manifestURI;
  5256.       if (OfflineApps._checkUsage(uri)) {
  5257.         var browser = this._getBrowserForCacheUpdate(cacheUpdate);
  5258.         if (browser) {
  5259.           OfflineApps._warnUsage(browser, cacheUpdate.manifestURI);
  5260.         }
  5261.       }
  5262.     }
  5263.   }
  5264. };
  5265.  
  5266. function WindowIsClosing()
  5267. {
  5268.   var browser = getBrowser();
  5269.   var cn = browser.tabContainer.childNodes;
  5270.   var numtabs = cn.length;
  5271.   var reallyClose = true;
  5272.  
  5273.   for (var i = 0; reallyClose && i < numtabs; ++i) {
  5274.     var ds = browser.getBrowserForTab(cn[i]).docShell;
  5275.  
  5276.     if (ds.contentViewer && !ds.contentViewer.permitUnload())
  5277.       reallyClose = false;
  5278.   }
  5279.  
  5280.   if (!reallyClose)
  5281.     return false;
  5282.  
  5283.   // closeWindow takes a second optional function argument to open up a
  5284.   // window closing warning dialog if we're not quitting. (Quitting opens
  5285.   // up another dialog so we don't need to.)
  5286.   return closeWindow(false,
  5287.     function () {
  5288.       return browser.warnAboutClosingTabs(true);
  5289.     });
  5290. }
  5291.  
  5292. var MailIntegration = {
  5293.   sendLinkForWindow: function (aWindow) {
  5294.     this.sendMessage(aWindow.location.href,
  5295.                      aWindow.document.title);
  5296.   },
  5297.  
  5298.   sendMessage: function (aBody, aSubject) {
  5299.     // generate a mailto url based on the url and the url's title
  5300.     var mailtoUrl = "mailto:";
  5301.     if (aBody) {
  5302.       mailtoUrl += "?body=" + encodeURIComponent(aBody);
  5303.       mailtoUrl += "&subject=" + encodeURIComponent(aSubject);
  5304.     }
  5305.  
  5306.     var ioService = Components.classes["@mozilla.org/network/io-service;1"]
  5307.                               .getService(Components.interfaces.nsIIOService);
  5308.     var uri = ioService.newURI(mailtoUrl, null, null);
  5309.  
  5310.     // now pass this uri to the operating system
  5311.     this._launchExternalUrl(uri);
  5312.   },
  5313.  
  5314.   // a generic method which can be used to pass arbitrary urls to the operating
  5315.   // system.
  5316.   // aURL --> a nsIURI which represents the url to launch
  5317.   _launchExternalUrl: function (aURL) {
  5318.     var extProtocolSvc =
  5319.        Components.classes["@mozilla.org/uriloader/external-protocol-service;1"]
  5320.                  .getService(Components.interfaces.nsIExternalProtocolService);
  5321.     if (extProtocolSvc)
  5322.       extProtocolSvc.loadUrl(aURL);
  5323.   }
  5324. };
  5325.  
  5326. function BrowserOpenAddonsMgr()
  5327. {
  5328.   const EMTYPE = "Extension:Manager";
  5329.   var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  5330.                      .getService(Components.interfaces.nsIWindowMediator);
  5331.   var theEM = wm.getMostRecentWindow(EMTYPE);
  5332.   if (theEM) {
  5333.     theEM.focus();
  5334.     return;
  5335.   }
  5336.  
  5337.   const EMURL = "chrome://mozapps/content/extensions/extensions.xul";
  5338.   const EMFEATURES = "chrome,menubar,extra-chrome,toolbar,dialog=no,resizable";
  5339.   window.openDialog(EMURL, "", EMFEATURES);
  5340. }
  5341.  
  5342. function escapeNameValuePair(aName, aValue, aIsFormUrlEncoded)
  5343. {
  5344.   if (aIsFormUrlEncoded)
  5345.     return escape(aName + "=" + aValue);
  5346.   else
  5347.     return escape(aName) + "=" + escape(aValue);
  5348. }
  5349.  
  5350. function AddKeywordForSearchField()
  5351. {
  5352.   var node = document.popupNode;
  5353.  
  5354.   var charset = node.ownerDocument.characterSet;
  5355.  
  5356.   var docURI = makeURI(node.ownerDocument.URL,
  5357.                        charset);
  5358.  
  5359.   var formURI = makeURI(node.form.getAttribute("action"),
  5360.                         charset,
  5361.                         docURI);
  5362.  
  5363.   var spec = formURI.spec;
  5364.  
  5365.   var isURLEncoded = 
  5366.                (node.form.method.toUpperCase() == "POST"
  5367.                 && (node.form.enctype == "application/x-www-form-urlencoded" ||
  5368.                     node.form.enctype == ""));
  5369.  
  5370.   var el, type;
  5371.   var formData = [];
  5372.  
  5373.   for (var i=0; i < node.form.elements.length; i++) {
  5374.     el = node.form.elements[i];
  5375.  
  5376.     if (!el.type) // happens with fieldsets
  5377.       continue;
  5378.  
  5379.     if (el == node) {
  5380.       formData.push((isURLEncoded) ? escapeNameValuePair(el.name, "%s", true) :
  5381.                                      // Don't escape "%s", just append
  5382.                                      escapeNameValuePair(el.name, "", false) + "%s");
  5383.       continue;
  5384.     }
  5385.  
  5386.     type = el.type.toLowerCase();
  5387.     
  5388.     if ((type == "text" || type == "hidden" || type == "textarea") ||
  5389.         ((type == "checkbox" || type == "radio") && el.checked)) {
  5390.       formData.push(escapeNameValuePair(el.name, el.value, isURLEncoded));
  5391.     } else if (el instanceof HTMLSelectElement && el.selectedIndex >= 0) {
  5392.       for (var j=0; j < el.options.length; j++) {
  5393.         if (el.options[j].selected)
  5394.           formData.push(escapeNameValuePair(el.name, el.options[j].value,
  5395.                                             isURLEncoded));
  5396.       }
  5397.     }
  5398.   }
  5399.  
  5400.   var postData;
  5401.  
  5402.   if (isURLEncoded)
  5403.     postData = formData.join("&");
  5404.   else
  5405.     spec += "?" + formData.join("&");
  5406.  
  5407.   var description = PlacesUIUtils.getDescriptionFromDocument(node.ownerDocument);
  5408.   PlacesUIUtils.showMinimalAddBookmarkUI(makeURI(spec), "", description, null,
  5409.                                          null, null, "", postData, charset);
  5410. }
  5411.  
  5412. function SwitchDocumentDirection(aWindow) {
  5413.   aWindow.document.dir = (aWindow.document.dir == "ltr" ? "rtl" : "ltr");
  5414.   for (var run = 0; run < aWindow.frames.length; run++)
  5415.     SwitchDocumentDirection(aWindow.frames[run]);
  5416. }
  5417.  
  5418. function missingPluginInstaller(){
  5419. }
  5420.  
  5421. function getPluginInfo(pluginElement)
  5422. {
  5423.   var tagMimetype;
  5424.   var pluginsPage;
  5425.   if (pluginElement instanceof HTMLAppletElement) {
  5426.     tagMimetype = "application/x-java-vm";
  5427.   } else {
  5428.     if (pluginElement instanceof HTMLObjectElement) {
  5429.       pluginsPage = pluginElement.getAttribute("codebase");
  5430.     } else {
  5431.       pluginsPage = pluginElement.getAttribute("pluginspage");
  5432.     }
  5433.  
  5434.     // only attempt if a pluginsPage is defined.
  5435.     if (pluginsPage) {
  5436.       var doc = pluginElement.ownerDocument;
  5437.       var docShell = findChildShell(doc, gBrowser.selectedBrowser.docShell, null);
  5438.       try {
  5439.         pluginsPage = makeURI(pluginsPage, doc.characterSet, docShell.currentURI).spec;
  5440.       } catch (ex) { 
  5441.         pluginsPage = "";
  5442.       }
  5443.     }
  5444.  
  5445.     tagMimetype = pluginElement.QueryInterface(Components.interfaces.nsIObjectLoadingContent)
  5446.                                .actualType;
  5447.  
  5448.     if (tagMimetype == "") {
  5449.       tagMimetype = pluginElement.type;
  5450.     }
  5451.   }
  5452.  
  5453.   return {mimetype: tagMimetype, pluginsPage: pluginsPage};
  5454. }
  5455.  
  5456. missingPluginInstaller.prototype.installSinglePlugin = function(aEvent){
  5457.   var tabbrowser = getBrowser();
  5458.   var missingPluginsArray = {};
  5459.  
  5460.   var pluginInfo = getPluginInfo(aEvent.target);
  5461.   missingPluginsArray[pluginInfo.mimetype] = pluginInfo;
  5462.  
  5463.   if (missingPluginsArray) {
  5464.     window.openDialog("chrome://mozapps/content/plugins/pluginInstallerWizard.xul",
  5465.                       "PFSWindow", "chrome,centerscreen,resizable=yes",
  5466.                       {plugins: missingPluginsArray, browser: tabbrowser.selectedBrowser});
  5467.   }
  5468.  
  5469.   aEvent.preventDefault();
  5470. }
  5471.  
  5472. missingPluginInstaller.prototype.newMissingPlugin = function(aEvent){
  5473.   // Since we are expecting also untrusted events, make sure
  5474.   // that the target is a plugin
  5475.   if (!(aEvent.target instanceof Components.interfaces.nsIObjectLoadingContent))
  5476.     return;
  5477.  
  5478.   // For broken non-object plugin tags, register a click handler so
  5479.   // that the user can click the plugin replacement to get the new
  5480.   // plugin. Object tags can, and often do, deal with that themselves,
  5481.   // so don't stomp on the page developers toes.
  5482.  
  5483.   if (aEvent.type != "PluginBlocklisted" &&
  5484.       !(aEvent.target instanceof HTMLObjectElement)) {
  5485.     aEvent.target.addEventListener("click",
  5486.                                    gMissingPluginInstaller.installSinglePlugin,
  5487.                                    false);
  5488.   }
  5489.  
  5490.   try {
  5491.     if (gPrefService.getBoolPref("plugins.hide_infobar_for_missing_plugin"))
  5492.       return;
  5493.   } catch (ex) {} // if the pref is missing, treat it as false, which shows the infobar
  5494.  
  5495.   var tabbrowser = getBrowser();
  5496.   const browsers = tabbrowser.mPanelContainer.childNodes;
  5497.  
  5498.   var contentWindow = aEvent.target.ownerDocument.defaultView.top;
  5499.  
  5500.   var i = 0;
  5501.   for (; i < browsers.length; i++) {
  5502.     if (tabbrowser.getBrowserAtIndex(i).contentWindow == contentWindow)
  5503.       break;
  5504.   }
  5505.  
  5506.   var browser = tabbrowser.getBrowserAtIndex(i);
  5507.   if (!browser.missingPlugins)
  5508.     browser.missingPlugins = {};
  5509.  
  5510.   var pluginInfo = getPluginInfo(aEvent.target);
  5511.  
  5512.   browser.missingPlugins[pluginInfo.mimetype] = pluginInfo;
  5513.  
  5514.   var notificationBox = gBrowser.getNotificationBox(browser);
  5515.  
  5516.   // If there is already a missing plugin notification then do nothing
  5517.   if (notificationBox.getNotificationWithValue("missing-plugins"))
  5518.     return;
  5519.  
  5520.   var bundle_browser = document.getElementById("bundle_browser");
  5521.   var blockedNotification = notificationBox.getNotificationWithValue("blocked-plugins");
  5522.   const priority = notificationBox.PRIORITY_WARNING_MEDIUM;
  5523.   const iconURL = "chrome://mozapps/skin/plugins/pluginGeneric-16.png";
  5524.  
  5525.   if (aEvent.type == "PluginBlocklisted" && !blockedNotification) {
  5526.     var messageString = bundle_browser.getString("blockedpluginsMessage.title");
  5527.     var buttons = [{
  5528.       label: bundle_browser.getString("blockedpluginsMessage.infoButton.label"),
  5529.       accessKey: bundle_browser.getString("blockedpluginsMessage.infoButton.accesskey"),
  5530.       popup: null,
  5531.       callback: blocklistInfo
  5532.     }, {
  5533.       label: bundle_browser.getString("blockedpluginsMessage.searchButton.label"),
  5534.       accessKey: bundle_browser.getString("blockedpluginsMessage.searchButton.accesskey"),
  5535.       popup: null,
  5536.       callback: pluginsMissing
  5537.     }];
  5538.  
  5539.     notificationBox.appendNotification(messageString, "blocked-plugins",
  5540.                                        iconURL, priority, buttons);
  5541.   }
  5542.  
  5543.   if (aEvent.type == "PluginNotFound") {
  5544.     // Cancel any notification about blocklisting
  5545.     if (blockedNotification)
  5546.       blockedNotification.close();
  5547.  
  5548.     var messageString = bundle_browser.getString("missingpluginsMessage.title");
  5549.     var buttons = [{
  5550.       label: bundle_browser.getString("missingpluginsMessage.button.label"),
  5551.       accessKey: bundle_browser.getString("missingpluginsMessage.button.accesskey"),
  5552.       popup: null,
  5553.       callback: pluginsMissing
  5554.     }];
  5555.  
  5556.     notificationBox.appendNotification(messageString, "missing-plugins",
  5557.                                        iconURL, priority, buttons);
  5558.   }
  5559. }
  5560.  
  5561. missingPluginInstaller.prototype.refreshBrowser = function(aEvent) {
  5562.   var browser = aEvent.target;
  5563.   var notificationBox = gBrowser.getNotificationBox(browser);
  5564.   var notification = notificationBox.getNotificationWithValue("missing-plugins");
  5565.  
  5566.   // clear the plugin list, now that at least one plugin has been installed
  5567.   browser.missingPlugins = null;
  5568.   if (notification) {
  5569.     // reset UI
  5570.     notificationBox.removeNotification(notification);
  5571.   }
  5572.   // reload the browser to make the new plugin show.
  5573.   browser.reload();
  5574. }
  5575.  
  5576. function blocklistInfo()
  5577. {
  5578.   var formatter = Components.classes["@mozilla.org/toolkit/URLFormatterService;1"]
  5579.                             .getService(Components.interfaces.nsIURLFormatter);
  5580.   var url = formatter.formatURLPref("extensions.blocklist.detailsURL");
  5581.   gBrowser.loadOneTab(url, null, null, null, false, false);
  5582.   return true;
  5583. }
  5584.  
  5585. function pluginsMissing()
  5586. {
  5587.   // get the urls of missing plugins
  5588.   var tabbrowser = getBrowser();
  5589.   var missingPluginsArray = tabbrowser.selectedBrowser.missingPlugins;
  5590.   if (missingPluginsArray) {
  5591.     window.openDialog("chrome://mozapps/content/plugins/pluginInstallerWizard.xul",
  5592.                       "PFSWindow", "chrome,centerscreen,resizable=yes",
  5593.                       {plugins: missingPluginsArray, browser: tabbrowser.selectedBrowser});
  5594.   }
  5595. }
  5596.  
  5597. var gMissingPluginInstaller = new missingPluginInstaller();
  5598.  
  5599. function convertFromUnicode(charset, str)
  5600. {
  5601.   try {
  5602.     var unicodeConverter = Components
  5603.        .classes["@mozilla.org/intl/scriptableunicodeconverter"]
  5604.        .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
  5605.     unicodeConverter.charset = charset;
  5606.     str = unicodeConverter.ConvertFromUnicode(str);
  5607.     return str + unicodeConverter.Finish();
  5608.   } catch(ex) {
  5609.     return null; 
  5610.   }
  5611. }
  5612.  
  5613. /**
  5614.  * The Feed Handler object manages discovery of RSS/ATOM feeds in web pages
  5615.  * and shows UI when they are discovered. 
  5616.  */
  5617. var FeedHandler = {
  5618.   /**
  5619.    * The click handler for the Feed icon in the location bar. Opens the
  5620.    * subscription page if user is not given a choice of feeds.
  5621.    * (Otherwise the list of available feeds will be presented to the 
  5622.    * user in a popup menu.)
  5623.    */
  5624.   onFeedButtonClick: function(event) {
  5625.     event.stopPropagation();
  5626.  
  5627.     if (event.target.hasAttribute("feed") &&
  5628.         event.eventPhase == Event.AT_TARGET &&
  5629.         (event.button == 0 || event.button == 1)) {
  5630.         this.subscribeToFeed(null, event);
  5631.     }
  5632.   },
  5633.   
  5634.   /**
  5635.    * Called when the user clicks on the Feed icon in the location bar. 
  5636.    * Builds a menu of unique feeds associated with the page, and if there
  5637.    * is only one, shows the feed inline in the browser window. 
  5638.    * @param   menuPopup
  5639.    *          The feed list menupopup to be populated.
  5640.    * @returns true if the menu should be shown, false if there was only
  5641.    *          one feed and the feed should be shown inline in the browser
  5642.    *          window (do not show the menupopup).
  5643.    */
  5644.   buildFeedList: function(menuPopup) {
  5645.     var feeds = gBrowser.selectedBrowser.feeds;
  5646.     if (feeds == null) {
  5647.       // XXX hack -- menu opening depends on setting of an "open"
  5648.       // attribute, and the menu refuses to open if that attribute is
  5649.       // set (because it thinks it's already open).  onpopupshowing gets
  5650.       // called after the attribute is unset, and it doesn't get unset
  5651.       // if we return false.  so we unset it here; otherwise, the menu
  5652.       // refuses to work past this point.
  5653.       menuPopup.parentNode.removeAttribute("open");
  5654.       return false;
  5655.     }
  5656.  
  5657.     while (menuPopup.firstChild)
  5658.       menuPopup.removeChild(menuPopup.firstChild);
  5659.  
  5660.     if (feeds.length == 1) {
  5661.       var feedButton = document.getElementById("feed-button");
  5662.       if (feedButton)
  5663.         feedButton.setAttribute("feed", feeds[0].href);
  5664.       return false;
  5665.     }
  5666.  
  5667.     // Build the menu showing the available feed choices for viewing. 
  5668.     for (var i = 0; i < feeds.length; ++i) {
  5669.       var feedInfo = feeds[i];
  5670.       var menuItem = document.createElement("menuitem");
  5671.       var baseTitle = feedInfo.title || feedInfo.href;
  5672.       var labelStr = gNavigatorBundle.getFormattedString("feedShowFeedNew", [baseTitle]);
  5673.       menuItem.setAttribute("label", labelStr);
  5674.       menuItem.setAttribute("feed", feedInfo.href);
  5675.       menuItem.setAttribute("tooltiptext", feedInfo.href);
  5676.       menuItem.setAttribute("crop", "center");
  5677.       menuPopup.appendChild(menuItem);
  5678.     }
  5679.     return true;
  5680.   },
  5681.   
  5682.   /**
  5683.    * Subscribe to a given feed.  Called when
  5684.    *   1. Page has a single feed and user clicks feed icon in location bar
  5685.    *   2. Page has a single feed and user selects Subscribe menu item
  5686.    *   3. Page has multiple feeds and user selects from feed icon popup
  5687.    *   4. Page has multiple feeds and user selects from Subscribe submenu
  5688.    * @param   href
  5689.    *          The feed to subscribe to. May be null, in which case the
  5690.    *          event target's feed attribute is examined.
  5691.    * @param   event
  5692.    *          The event this method is handling. Used to decide where 
  5693.    *          to open the preview UI. (Optional, unless href is null)
  5694.    */
  5695.   subscribeToFeed: function(href, event) {
  5696.     // Just load the feed in the content area to either subscribe or show the
  5697.     // preview UI
  5698.     if (!href)
  5699.       href = event.target.getAttribute("feed");
  5700.     urlSecurityCheck(href, gBrowser.contentPrincipal,
  5701.                      Ci.nsIScriptSecurityManager.DISALLOW_INHERIT_PRINCIPAL);
  5702.     var feedURI = makeURI(href, document.characterSet);
  5703.     // Use the feed scheme so X-Moz-Is-Feed will be set
  5704.     // The value doesn't matter
  5705.     if (/^https?/.test(feedURI.scheme))
  5706.       href = "feed:" + href;
  5707.     this.loadFeed(href, event);
  5708.   },
  5709.  
  5710.   loadFeed: function(href, event) {
  5711.     var feeds = gBrowser.selectedBrowser.feeds;
  5712.     try {
  5713.       openUILink(href, event, false, true, false, null);
  5714.     }
  5715.     finally {
  5716.       // We might default to a livebookmarks modal dialog, 
  5717.       // so reset that if the user happens to click it again
  5718.       gBrowser.selectedBrowser.feeds = feeds;
  5719.     }
  5720.   },
  5721.  
  5722.   /**
  5723.    * Update the browser UI to show whether or not feeds are available when
  5724.    * a page is loaded or the user switches tabs to a page that has feeds. 
  5725.    */
  5726.   updateFeeds: function() {
  5727.     var feedButton = document.getElementById("feed-button");
  5728.     if (!this._feedMenuitem)
  5729.       this._feedMenuitem = document.getElementById("subscribeToPageMenuitem");
  5730.     if (!this._feedMenupopup)
  5731.       this._feedMenupopup = document.getElementById("subscribeToPageMenupopup");
  5732.  
  5733.     var feeds = gBrowser.mCurrentBrowser.feeds;
  5734.     if (!feeds || feeds.length == 0) {
  5735.       if (feedButton) {
  5736.         feedButton.removeAttribute("feeds");
  5737.         feedButton.removeAttribute("feed");
  5738.         feedButton.setAttribute("tooltiptext", 
  5739.                                 gNavigatorBundle.getString("feedNoFeeds"));
  5740.       }
  5741.       this._feedMenuitem.setAttribute("disabled", "true");
  5742.       this._feedMenupopup.setAttribute("hidden", "true");
  5743.       this._feedMenuitem.removeAttribute("hidden");
  5744.     } else {
  5745.       if (feedButton) {
  5746.         feedButton.setAttribute("feeds", "true");
  5747.         feedButton.setAttribute("tooltiptext", 
  5748.                                 gNavigatorBundle.getString("feedHasFeedsNew"));
  5749.       }
  5750.       
  5751.       if (feeds.length > 1) {
  5752.         this._feedMenuitem.setAttribute("hidden", "true");
  5753.         this._feedMenupopup.removeAttribute("hidden");
  5754.         if (feedButton)
  5755.           feedButton.removeAttribute("feed");
  5756.       } else {
  5757.         if (feedButton)
  5758.           feedButton.setAttribute("feed", feeds[0].href);
  5759.  
  5760.         this._feedMenuitem.setAttribute("feed", feeds[0].href);
  5761.         this._feedMenuitem.removeAttribute("disabled");
  5762.         this._feedMenuitem.removeAttribute("hidden");
  5763.         this._feedMenupopup.setAttribute("hidden", "true");
  5764.       }
  5765.     }
  5766.   }, 
  5767.  
  5768.   addFeed: function(feed, targetDoc) {
  5769.     if (feed) {
  5770.       // find which tab this is for, and set the attribute on the browser
  5771.       var browserForLink = gBrowser.getBrowserForDocument(targetDoc);
  5772.       if (!browserForLink) {
  5773.         // ??? this really shouldn't happen..
  5774.         return;
  5775.       }
  5776.  
  5777.       var feeds = [];
  5778.       if (browserForLink.feeds != null)
  5779.         feeds = browserForLink.feeds;
  5780.  
  5781.       feeds.push(feed);
  5782.       browserForLink.feeds = feeds;
  5783.       if (browserForLink == gBrowser || browserForLink == gBrowser.mCurrentBrowser) {
  5784.         var feedButton = document.getElementById("feed-button");
  5785.         if (feedButton) {
  5786.           feedButton.setAttribute("feeds", "true");
  5787.           feedButton.setAttribute("tooltiptext", 
  5788.                                   gNavigatorBundle.getString("feedHasFeedsNew"));
  5789.         }
  5790.       }
  5791.     }
  5792.   }
  5793. };
  5794.  
  5795. //@line 39 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser-places.js"
  5796.  
  5797.  
  5798. var StarUI = {
  5799.   _itemId: -1,
  5800.   uri: null,
  5801.   _batching: false,
  5802.  
  5803.   // nsISupports
  5804.   QueryInterface: function SU_QueryInterface(aIID) {
  5805.     if (aIID.equals(Ci.nsIDOMEventListener) ||
  5806.         aIID.equals(Ci.nsISupports))
  5807.       return this;
  5808.  
  5809.     throw Cr.NS_NOINTERFACE;
  5810.   },
  5811.  
  5812.   _element: function(aID) {
  5813.     return document.getElementById(aID);
  5814.   },
  5815.  
  5816.   // Edit-bookmark panel
  5817.   get panel() {
  5818.     delete this.panel;
  5819.     var element = this._element("editBookmarkPanel");
  5820.     // initially the panel is hidden
  5821.     // to avoid impacting startup / new window performance
  5822.     element.hidden = false;
  5823.     element.addEventListener("popuphidden", this, false);
  5824.     element.addEventListener("keypress", this, true);
  5825.     return this.panel = element;
  5826.   },
  5827.  
  5828.   // list of command elements (by id) to disable when the panel is opened
  5829.   _blockedCommands: ["cmd_close", "cmd_closeWindow"],
  5830.   _blockCommands: function SU__blockCommands() {
  5831.     for each(var key in this._blockedCommands) {
  5832.       var elt = this._element(key);
  5833.       // make sure not to permanently disable this item (see bug 409155)
  5834.       if (elt.hasAttribute("wasDisabled"))
  5835.         continue;
  5836.       if (elt.getAttribute("disabled") == "true")
  5837.         elt.setAttribute("wasDisabled", "true");
  5838.       else {
  5839.         elt.setAttribute("wasDisabled", "false");
  5840.         elt.setAttribute("disabled", "true");
  5841.       }
  5842.     }
  5843.   },
  5844.  
  5845.   _restoreCommandsState: function SU__restoreCommandsState() {
  5846.     for each(var key in this._blockedCommands) {
  5847.       var elt = this._element(key);
  5848.       if (elt.getAttribute("wasDisabled") != "true")
  5849.         elt.removeAttribute("disabled");
  5850.       elt.removeAttribute("wasDisabled");
  5851.     }
  5852.   },
  5853.  
  5854.   // nsIDOMEventListener
  5855.   handleEvent: function SU_handleEvent(aEvent) {
  5856.     switch (aEvent.type) {
  5857.       case "popuphidden":
  5858.         if (aEvent.originalTarget == this.panel) {
  5859.           if (!this._element("editBookmarkPanelContent").hidden)
  5860.             this.quitEditMode();
  5861.           this._restoreCommandsState();
  5862.           this._itemId = -1;
  5863.           this._uri = null;
  5864.           if (this._batching) {
  5865.             PlacesUIUtils.ptm.endBatch();
  5866.             this._batching = false;
  5867.           }
  5868.         }
  5869.         break;
  5870.       case "keypress":
  5871.         if (aEvent.keyCode == KeyEvent.DOM_VK_ESCAPE) {
  5872.           // In edit mode, if we're not editing a folder, the ESC key is mapped
  5873.           // to the cancel button
  5874.           if (!this._element("editBookmarkPanelContent").hidden) {
  5875.             var elt = aEvent.target;
  5876.             if (elt.localName != "tree" ||
  5877.                 (elt.localName == "tree" && !elt.hasAttribute("editing")))
  5878.               this.cancelButtonOnCommand();
  5879.           }
  5880.         }
  5881.         else if (aEvent.keyCode == KeyEvent.DOM_VK_RETURN) {
  5882.           // hide the panel unless the folder tree is focused
  5883.           if (aEvent.target.localName != "tree")
  5884.             this.panel.hidePopup();
  5885.         }
  5886.         break;
  5887.     }
  5888.   },
  5889.  
  5890.   _overlayLoaded: false,
  5891.   _overlayLoading: false,
  5892.   showEditBookmarkPopup:
  5893.   function SU_showEditBookmarkPopup(aItemId, aAnchorElement, aPosition) {
  5894.     // Performance: load the overlay the first time the panel is opened
  5895.     // (see bug 392443).
  5896.     if (this._overlayLoading)
  5897.       return;
  5898.  
  5899.     if (this._overlayLoaded) {
  5900.       this._doShowEditBookmarkPanel(aItemId, aAnchorElement, aPosition);
  5901.       return;
  5902.     }
  5903.  
  5904.     var loadObserver = {
  5905.       _self: this,
  5906.       _itemId: aItemId,
  5907.       _anchorElement: aAnchorElement,
  5908.       _position: aPosition,
  5909.       observe: function (aSubject, aTopic, aData) {
  5910.         this._self._overlayLoading = false;
  5911.         this._self._overlayLoaded = true;
  5912.         this._self._doShowEditBookmarkPanel(this._itemId, this._anchorElement,
  5913.                                             this._position);
  5914.       }
  5915.     };
  5916.     this._overlayLoading = true;
  5917.     document.loadOverlay("chrome://browser/content/places/editBookmarkOverlay.xul",
  5918.                          loadObserver);
  5919.   },
  5920.  
  5921.   _doShowEditBookmarkPanel:
  5922.   function SU__doShowEditBookmarkPanel(aItemId, aAnchorElement, aPosition) {
  5923.     this._blockCommands(); // un-done in the popuphiding handler
  5924.  
  5925.     var bundle = this._element("bundle_browser");
  5926.  
  5927.     // Set panel title:
  5928.     // if we are batching, i.e. the bookmark has been added now,
  5929.     // then show Page Bookmarked, else if the bookmark did already exist,
  5930.     // we are about editing it, then use Edit This Bookmark.
  5931.     this._element("editBookmarkPanelTitle").value =
  5932.       this._batching ?
  5933.         bundle.getString("editBookmarkPanel.pageBookmarkedTitle") :
  5934.         bundle.getString("editBookmarkPanel.editBookmarkTitle");
  5935.  
  5936.     // No description; show the Done, Cancel;
  5937.     // hide the Edit, Undo buttons
  5938.     this._element("editBookmarkPanelDescription").textContent = "";
  5939.     this._element("editBookmarkPanelBottomButtons").hidden = false;
  5940.     this._element("editBookmarkPanelContent").hidden = false;
  5941.     this._element("editBookmarkPanelEditButton").hidden = true;
  5942.     this._element("editBookmarkPanelUndoRemoveButton").hidden = true;
  5943.  
  5944.     // The remove button is shown only if we're not already batching, i.e.
  5945.     // if the cancel button/ESC does not remove the bookmark.
  5946.     this._element("editBookmarkPanelRemoveButton").hidden = this._batching;
  5947.  
  5948.     // unset the unstarred state, if set
  5949.     this._element("editBookmarkPanelStarIcon").removeAttribute("unstarred");
  5950.  
  5951.     this._itemId = aItemId !== undefined ? aItemId : this._itemId;
  5952.     this.beginBatch();
  5953.  
  5954.     // XXXmano hack: We push a no-op transaction on the stack so it's always
  5955.     // safe for the Cancel button to call undoTransaction after endBatch.
  5956.     // Otherwise, if no changes were done in the edit-item panel, the last
  5957.     // transaction on the undo stack may be the initial createItem transaction,
  5958.     // or worse, the batched editing of some other item.
  5959.     PlacesUIUtils.ptm.doTransaction({ doTransaction: function() { },
  5960.                                       undoTransaction: function() { },
  5961.                                       redoTransaction: function() { },
  5962.                                       isTransient: false,
  5963.                                       merge: function() { return false; } });
  5964.  
  5965.     if (this.panel.state == "closed") {
  5966.       // Consume dismiss clicks, see bug 400924
  5967.       this.panel.popupBoxObject
  5968.           .setConsumeRollupEvent(Ci.nsIPopupBoxObject.ROLLUP_CONSUME);
  5969.       this.panel.openPopup(aAnchorElement, aPosition, -1, -1);
  5970.     }
  5971.     else {
  5972.       var namePicker = this._element("editBMPanel_namePicker");
  5973.       namePicker.focus();
  5974.       namePicker.editor.selectAll();
  5975.     }
  5976.  
  5977.     gEditItemOverlay.initPanel(this._itemId,
  5978.                                { hiddenRows: ["description", "location",
  5979.                                               "loadInSidebar", "keyword"] });
  5980.   },
  5981.  
  5982.   panelShown:
  5983.   function SU_panelShown(aEvent) {
  5984.     if (aEvent.target == this.panel) {
  5985.       if (!this._element("editBookmarkPanelContent").hidden) {
  5986.         var namePicker = this._element("editBMPanel_namePicker");
  5987.         namePicker.focus();
  5988.         namePicker.editor.selectAll();
  5989.       }
  5990.       else
  5991.         this.panel.focus();
  5992.     }
  5993.   },
  5994.  
  5995.   showPageBookmarkedNotification:
  5996.   function PCH_showPageBookmarkedNotification(aItemId, aAnchorElement, aPosition) {
  5997.     this._blockCommands(); // un-done in the popuphiding handler
  5998.  
  5999.     var bundle = this._element("bundle_browser");
  6000.     var brandBundle = this._element("bundle_brand");
  6001.     var brandShortName = brandBundle.getString("brandShortName");
  6002.  
  6003.     // "Page Bookmarked" title
  6004.     this._element("editBookmarkPanelTitle").value =
  6005.       bundle.getString("editBookmarkPanel.pageBookmarkedTitle");
  6006.  
  6007.     // description
  6008.     this._element("editBookmarkPanelDescription").textContent =
  6009.       bundle.getFormattedString("editBookmarkPanel.pageBookmarkedDescription",
  6010.                                 [brandShortName]);
  6011.  
  6012.     // show the "Edit.." button and the Remove Bookmark button, hide the
  6013.     // undo-remove-bookmark button.
  6014.     this._element("editBookmarkPanelEditButton").hidden = false;
  6015.     this._element("editBookmarkPanelRemoveButton").hidden = false;
  6016.     this._element("editBookmarkPanelUndoRemoveButton").hidden = true;
  6017.  
  6018.     // unset the unstarred state, if set
  6019.     this._element("editBookmarkPanelStarIcon").removeAttribute("unstarred");
  6020.  
  6021.     this._itemId = aItemId !== undefined ? aItemId : this._itemId;
  6022.     if (this.panel.state == "closed") {
  6023.       // Consume dismiss clicks, see bug 400924
  6024.       this.panel.popupBoxObject
  6025.           .setConsumeRollupEvent(Ci.nsIPopupBoxObject.ROLLUP_CONSUME);
  6026.       this.panel.openPopup(aAnchorElement, aPosition, -1, -1);
  6027.     }
  6028.     else
  6029.       this.panel.focus();
  6030.   },
  6031.  
  6032.   quitEditMode: function SU_quitEditMode() {
  6033.     this._element("editBookmarkPanelContent").hidden = true;
  6034.     this._element("editBookmarkPanelBottomButtons").hidden = true;
  6035.     gEditItemOverlay.uninitPanel(true);
  6036.   },
  6037.  
  6038.   editButtonCommand: function SU_editButtonCommand() {
  6039.     this.showEditBookmarkPopup();
  6040.   },
  6041.  
  6042.   cancelButtonOnCommand: function SU_cancelButtonOnCommand() {
  6043.     // The order here is important! We have to hide the panel first, otherwise
  6044.     // changes done as part of Undo may change the panel contents and by
  6045.     // that force it to commit more transactions
  6046.     this.panel.hidePopup();
  6047.     this.endBatch();
  6048.     PlacesUIUtils.ptm.undoTransaction();
  6049.   },
  6050.  
  6051.   removeBookmarkButtonCommand: function SU_removeBookmarkButtonCommand() {
  6052. //@line 321 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser-places.js"
  6053.  
  6054.     // cache its uri so we can get the new itemId in the case of undo
  6055.     this._uri = PlacesUtils.bookmarks.getBookmarkURI(this._itemId);
  6056.  
  6057.     // remove all bookmarks for the bookmark's url, this also removes
  6058.     // the tags for the url
  6059.     var itemIds = PlacesUtils.getBookmarksForURI(this._uri);
  6060.     for (var i=0; i < itemIds.length; i++) {
  6061.       var txn = PlacesUIUtils.ptm.removeItem(itemIds[i]);
  6062.       PlacesUIUtils.ptm.doTransaction(txn);
  6063.     }
  6064.  
  6065. //@line 338 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser-places.js"
  6066.       this.panel.hidePopup();
  6067.   },
  6068.  
  6069.   undoRemoveBookmarkCommand: function SU_undoRemoveBookmarkCommand() {
  6070.     // restore the bookmark by undoing the last transaction and go back
  6071.     // to the edit state
  6072.     this.endBatch();
  6073.     PlacesUIUtils.ptm.undoTransaction();
  6074.     this._itemId = PlacesUtils.getMostRecentBookmarkForURI(this._uri);
  6075.     this.showEditBookmarkPopup();
  6076.   },
  6077.  
  6078.   beginBatch: function SU_beginBatch() {
  6079.     if (!this._batching) {
  6080.       PlacesUIUtils.ptm.beginBatch();
  6081.       this._batching = true;
  6082.     }
  6083.   },
  6084.  
  6085.   endBatch: function SU_endBatch() {
  6086.     if (this._batching) {
  6087.       PlacesUIUtils.ptm.endBatch();
  6088.       this._batching = false;
  6089.     }
  6090.   }
  6091. }
  6092.  
  6093. var PlacesCommandHook = {
  6094.   /**
  6095.    * Adds a bookmark to the page loaded in the given browser.
  6096.    *
  6097.    * @param aBrowser
  6098.    *        a <browser> element.
  6099.    * @param [optional] aParent
  6100.    *        The folder in which to create a new bookmark if the page loaded in
  6101.    *        aBrowser isn't bookmarked yet, defaults to the unfiled root.
  6102.    * @param [optional] aShowEditUI
  6103.    *        whether or not to show the edit-bookmark UI for the bookmark item
  6104.    */  
  6105.   bookmarkPage: function PCH_bookmarkPage(aBrowser, aParent, aShowEditUI) {
  6106.     var uri = aBrowser.currentURI;
  6107.     var itemId = PlacesUtils.getMostRecentBookmarkForURI(uri);
  6108.     if (itemId == -1) {
  6109.       // Copied over from addBookmarkForBrowser:
  6110.       // Bug 52536: We obtain the URL and title from the nsIWebNavigation
  6111.       // associated with a <browser/> rather than from a DOMWindow.
  6112.       // This is because when a full page plugin is loaded, there is
  6113.       // no DOMWindow (?) but information about the loaded document
  6114.       // may still be obtained from the webNavigation.
  6115.       var webNav = aBrowser.webNavigation;
  6116.       var url = webNav.currentURI;
  6117.       var title;
  6118.       var description;
  6119.       var charset;
  6120.       try {
  6121.         title = webNav.document.title || url.spec;
  6122.         description = PlacesUIUtils.getDescriptionFromDocument(webNav.document);
  6123.         charset = webNav.document.characterSet;
  6124.       }
  6125.       catch (e) { }
  6126.  
  6127.       if (aShowEditUI) {
  6128.         // If we bookmark the page here (i.e. page was not "starred" already)
  6129.         // but open right into the "edit" state, start batching here, so
  6130.         // "Cancel" in that state removes the bookmark.
  6131.         StarUI.beginBatch();
  6132.       }
  6133.  
  6134.       var parent = aParent != undefined ?
  6135.                    aParent : PlacesUtils.unfiledBookmarksFolderId;
  6136.       var descAnno = { name: DESCRIPTION_ANNO, value: description };
  6137.       var txn = PlacesUIUtils.ptm.createItem(uri, parent, -1,
  6138.                                              title, null, [descAnno]);
  6139.       PlacesUIUtils.ptm.doTransaction(txn);
  6140.       // Set the character-set
  6141.       if (charset)
  6142.         PlacesUtils.history.setCharsetForURI(uri, charset);
  6143.       itemId = PlacesUtils.getMostRecentBookmarkForURI(uri);
  6144.     }
  6145.  
  6146.     // Revert the contents of the location bar
  6147.     handleURLBarRevert();
  6148.  
  6149.     // dock the panel to the star icon when possible, otherwise dock
  6150.     // it to the content area
  6151.     if (aBrowser.contentWindow == window.content) {
  6152.       var starIcon = aBrowser.ownerDocument.getElementById("star-button");
  6153.       if (starIcon && isElementVisible(starIcon)) {
  6154.         if (aShowEditUI)
  6155.           StarUI.showEditBookmarkPopup(itemId, starIcon, "after_end");
  6156. //@line 432 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser-places.js"
  6157.         return;
  6158.       }
  6159.     }
  6160.  
  6161.     StarUI.showEditBookmarkPopup(itemId, aBrowser, "overlap");
  6162.   },
  6163.  
  6164.   /**
  6165.    * Adds a bookmark to the page loaded in the current tab. 
  6166.    */
  6167.   bookmarkCurrentPage: function PCH_bookmarkCurrentPage(aShowEditUI, aParent) {
  6168.     this.bookmarkPage(getBrowser().selectedBrowser, aParent, aShowEditUI);
  6169.   },
  6170.  
  6171.   /**
  6172.    * Adds a bookmark to the page targeted by a link.
  6173.    * @param aParent
  6174.    *        The folder in which to create a new bookmark if aURL isn't
  6175.    *        bookmarked.
  6176.    * @param aURL (string)
  6177.    *        the address of the link target
  6178.    * @param aTitle
  6179.    *        The link text
  6180.    */
  6181.   bookmarkLink: function PCH_bookmarkLink(aParent, aURL, aTitle) {
  6182.     var linkURI = makeURI(aURL);
  6183.     var itemId = PlacesUtils.getMostRecentBookmarkForURI(linkURI);
  6184.     if (itemId == -1) {
  6185.       StarUI.beginBatch();
  6186.       var txn = PlacesUIUtils.ptm.createItem(linkURI, aParent, -1, aTitle);
  6187.       PlacesUIUtils.ptm.doTransaction(txn);
  6188.       itemId = PlacesUtils.getMostRecentBookmarkForURI(linkURI);
  6189.     }
  6190.  
  6191.     StarUI.showEditBookmarkPopup(itemId, getBrowser(), "overlap");
  6192.   },
  6193.  
  6194.   /**
  6195.    * This function returns a list of nsIURI objects characterizing the
  6196.    * tabs currently open in the browser.  The URIs will appear in the
  6197.    * list in the order in which their corresponding tabs appeared.  However,
  6198.    * only the first instance of each URI will be returned.
  6199.    *
  6200.    * @returns a list of nsIURI objects representing unique locations open
  6201.    */
  6202.   _getUniqueTabInfo: function BATC__getUniqueTabInfo() {
  6203.     var tabList = [];
  6204.     var seenURIs = [];
  6205.  
  6206.     var browsers = getBrowser().browsers;
  6207.     for (var i = 0; i < browsers.length; ++i) {
  6208.       var webNav = browsers[i].webNavigation;
  6209.       var uri = webNav.currentURI;
  6210.  
  6211.       // skip redundant entries
  6212.       if (uri.spec in seenURIs)
  6213.         continue;
  6214.  
  6215.       // add to the set of seen URIs
  6216.       seenURIs[uri.spec] = true;
  6217.       tabList.push(uri);
  6218.     }
  6219.     return tabList;
  6220.   },
  6221.  
  6222.   /**
  6223.    * Adds a folder with bookmarks to all of the currently open tabs in this 
  6224.    * window.
  6225.    */
  6226.   bookmarkCurrentPages: function PCH_bookmarkCurrentPages() {
  6227.     var tabURIs = this._getUniqueTabInfo();
  6228.     PlacesUIUtils.showMinimalAddMultiBookmarkUI(tabURIs);
  6229.   },
  6230.  
  6231.   
  6232.   /**
  6233.    * Adds a Live Bookmark to a feed associated with the current page. 
  6234.    * @param     url
  6235.    *            The nsIURI of the page the feed was attached to
  6236.    * @title     title
  6237.    *            The title of the feed. Optional.
  6238.    * @subtitle  subtitle
  6239.    *            A short description of the feed. Optional.
  6240.    */
  6241.   addLiveBookmark: function PCH_addLiveBookmark(url, feedTitle, feedSubtitle) {
  6242.     var ios = 
  6243.         Cc["@mozilla.org/network/io-service;1"].
  6244.         getService(Ci.nsIIOService);
  6245.     var feedURI = ios.newURI(url, null, null);
  6246.     
  6247.     var doc = gBrowser.contentDocument;
  6248.     var title = (arguments.length > 1) ? feedTitle : doc.title;
  6249.  
  6250.     var description;
  6251.     if (arguments.length > 2)
  6252.       description = feedSubtitle;
  6253.     else
  6254.       description = PlacesUIUtils.getDescriptionFromDocument(doc);
  6255.  
  6256.     var toolbarIP =
  6257.       new InsertionPoint(PlacesUtils.bookmarks.toolbarFolder, -1);
  6258.     PlacesUIUtils.showMinimalAddLivemarkUI(feedURI, gBrowser.currentURI,
  6259.                                            title, description, toolbarIP, true);
  6260.   },
  6261.  
  6262.   /**
  6263.    * Opens the Places Organizer. 
  6264.    * @param   aLeftPaneRoot
  6265.    *          The query to select in the organizer window - options
  6266.    *          are: History, AllBookmarks, BookmarksMenu, BookmarksToolbar,
  6267.    *          UnfiledBookmarks and Tags.
  6268.    */
  6269.   showPlacesOrganizer: function PCH_showPlacesOrganizer(aLeftPaneRoot) {
  6270.     var wm = Cc["@mozilla.org/appshell/window-mediator;1"].
  6271.              getService(Ci.nsIWindowMediator);
  6272.     var organizer = wm.getMostRecentWindow("Places:Organizer");
  6273.     if (!organizer) {
  6274.       // No currently open places window, so open one with the specified mode.
  6275.       openDialog("chrome://browser/content/places/places.xul", 
  6276.                  "", "chrome,toolbar=yes,dialog=no,resizable", aLeftPaneRoot);
  6277.     }
  6278.     else {
  6279.       organizer.PlacesOrganizer.selectLeftPaneQuery(aLeftPaneRoot);
  6280.       organizer.focus();
  6281.     }
  6282.   },
  6283.  
  6284.   deleteButtonOnCommand: function PCH_deleteButtonCommand() {
  6285.     PlacesUtils.bookmarks.removeItem(gEditItemOverlay.itemId);
  6286.  
  6287.     // remove all tags for the associated url
  6288.     PlacesUtils.tagging.untagURI(gEditItemOverlay._uri, null);
  6289.  
  6290.     this.panel.hidePopup();
  6291.   }
  6292. };
  6293.  
  6294. // Functions for the history menu.
  6295. var HistoryMenu = {
  6296.   /**
  6297.    * popupshowing handler for the history menu.
  6298.    * @param aMenuPopup
  6299.    *        XULNode for the history menupopup
  6300.    */
  6301.   onPopupShowing: function PHM_onPopupShowing(aMenuPopup) {
  6302.     var resultNode = aMenuPopup.getResultNode();
  6303.     var wasOpen = resultNode.containerOpen;
  6304.     resultNode.containerOpen = true;
  6305.     document.getElementById("endHistorySeparator").hidden =
  6306.       resultNode.childCount == 0;
  6307.  
  6308.     if (!wasOpen)
  6309.       resultNode.containerOpen = false;
  6310.  
  6311.     // HistoryMenu.toggleRecentlyClosedTabs is defined in browser.js
  6312.     this.toggleRecentlyClosedTabs();
  6313.   }
  6314. };
  6315.  
  6316. /**
  6317.  * Functions for handling events in the Bookmarks Toolbar and menu.
  6318.  */
  6319. var BookmarksEventHandler = {  
  6320.   /**
  6321.    * Handler for click event for an item in the bookmarks toolbar or menu.
  6322.    * Menus and submenus from the folder buttons bubble up to this handler.
  6323.    * Left-click is handled in the onCommand function.
  6324.    * When items are middle-clicked (or clicked with modifier), open in tabs.
  6325.    * If the click came through a menu, close the menu.
  6326.    * @param aEvent
  6327.    *        DOMEvent for the click
  6328.    */
  6329.   onClick: function BT_onClick(aEvent) {
  6330.     // Only handle middle-click or left-click with modifiers.
  6331. //@line 609 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser-places.js"
  6332.     var modifKey = aEvent.ctrlKey || aEvent.shiftKey;
  6333. //@line 611 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser-places.js"
  6334.     if (aEvent.button == 2 || (aEvent.button == 0 && !modifKey))
  6335.       return;
  6336.  
  6337.     var target = aEvent.originalTarget;
  6338.     // If this event bubbled up from a menu or menuitem, close the menus.
  6339.     // Do this before opening tabs, to avoid hiding the open tabs confirm-dialog.
  6340.     if (target.localName == "menu" || target.localName == "menuitem") {
  6341.       for (node = target.parentNode; node; node = node.parentNode) {
  6342.         if (node.localName == "menupopup")
  6343.           node.hidePopup();
  6344.         else if (node.localName != "menu")
  6345.           break;
  6346.       }
  6347.     }
  6348.  
  6349.     if (target.node && PlacesUtils.nodeIsContainer(target.node)) {
  6350.       // Don't open the root folder in tabs when the empty area on the toolbar
  6351.       // is middle-clicked or when a non-bookmark item except for Open in Tabs)
  6352.       // in a bookmarks menupopup is middle-clicked.
  6353.       if (target.localName == "menu" || target.localName == "toolbarbutton")
  6354.         PlacesUIUtils.openContainerNodeInTabs(target.node, aEvent);
  6355.     }
  6356.     else if (aEvent.button == 1) {
  6357.       // left-clicks with modifier are already served by onCommand
  6358.       this.onCommand(aEvent);
  6359.     }
  6360.   },
  6361.  
  6362.   /**
  6363.    * Handler for command event for an item in the bookmarks toolbar.
  6364.    * Menus and submenus from the folder buttons bubble up to this handler.
  6365.    * Opens the item.
  6366.    * @param aEvent 
  6367.    *        DOMEvent for the command
  6368.    */
  6369.   onCommand: function BM_onCommand(aEvent) {
  6370.     var target = aEvent.originalTarget;
  6371.     if (target.node)
  6372.       PlacesUIUtils.openNodeWithEvent(target.node, aEvent);
  6373.   },
  6374.  
  6375.   /**
  6376.    * Handler for popupshowing event for an item in bookmarks toolbar or menu.
  6377.    * If the item isn't the main bookmarks menu, add an "Open All in Tabs"
  6378.    * menuitem to the bottom of the popup.
  6379.    * @param event 
  6380.    *        DOMEvent for popupshowing
  6381.    */
  6382.   onPopupShowing: function BM_onPopupShowing(event) {
  6383.     var target = event.originalTarget;
  6384.     if (!target.hasAttribute("placespopup"))
  6385.       return;
  6386.  
  6387.     // Check if the popup contains at least 2 menuitems with places nodes
  6388.     var numNodes = 0;
  6389.     var hasMultipleURIs = false;
  6390.     var currentChild = target.firstChild;
  6391.     while (currentChild) {
  6392.       if (currentChild.localName == "menuitem" && currentChild.node) {
  6393.         if (++numNodes == 2) {
  6394.           hasMultipleURIs = true;
  6395.           break;
  6396.         }
  6397.       }
  6398.       currentChild = currentChild.nextSibling;
  6399.     }
  6400.  
  6401.     var itemId = target._resultNode.itemId;
  6402.     var siteURIString = "";
  6403.     if (itemId != -1 && PlacesUtils.livemarks.isLivemark(itemId)) {
  6404.       var siteURI = PlacesUtils.livemarks.getSiteURI(itemId);
  6405.       if (siteURI)
  6406.         siteURIString = siteURI.spec;
  6407.     }
  6408.  
  6409.     if (!siteURIString && target._endOptOpenSiteURI) {
  6410.         target.removeChild(target._endOptOpenSiteURI);
  6411.         target._endOptOpenSiteURI = null;
  6412.     }
  6413.  
  6414.     if (!hasMultipleURIs && target._endOptOpenAllInTabs) {
  6415.       target.removeChild(target._endOptOpenAllInTabs);
  6416.       target._endOptOpenAllInTabs = null;
  6417.     }
  6418.  
  6419.     if (!(hasMultipleURIs || siteURIString)) {
  6420.       // we don't have to show any option
  6421.       if (target._endOptSeparator) {
  6422.         target.removeChild(target._endOptSeparator);
  6423.         target._endOptSeparator = null;
  6424.         target._endMarker = -1;
  6425.       }
  6426.       return;
  6427.     }
  6428.  
  6429.     if (!target._endOptSeparator) {
  6430.       // create a separator before options
  6431.       target._endOptSeparator = document.createElement("menuseparator");
  6432.       target._endOptSeparator.setAttribute("builder", "end");
  6433.       target._endMarker = target.childNodes.length;
  6434.       target.appendChild(target._endOptSeparator);
  6435.     }
  6436.  
  6437.     if (siteURIString && !target._endOptOpenSiteURI) {
  6438.       // Add "Open (Feed Name)" menuitem if it's a livemark with a siteURI
  6439.       target._endOptOpenSiteURI = document.createElement("menuitem");
  6440.       target._endOptOpenSiteURI.setAttribute("siteURI", siteURIString);
  6441.       target._endOptOpenSiteURI.setAttribute("oncommand",
  6442.           "openUILink(this.getAttribute('siteURI'), event);");
  6443.       // If a user middle-clicks this item we serve the oncommand event
  6444.       // We are using checkForMiddleClick because of Bug 246720
  6445.       // Note: stopPropagation is needed to avoid serving middle-click 
  6446.       // with BT_onClick that would open all items in tabs
  6447.       target._endOptOpenSiteURI.setAttribute("onclick",
  6448.           "checkForMiddleClick(this, event); event.stopPropagation();");
  6449.       target._endOptOpenSiteURI.setAttribute("label",
  6450.           PlacesUIUtils.getFormattedString("menuOpenLivemarkOrigin.label",
  6451.           [target.parentNode.getAttribute("label")]));
  6452.       target.appendChild(target._endOptOpenSiteURI);
  6453.     }
  6454.  
  6455.     if (hasMultipleURIs && !target._endOptOpenAllInTabs) {
  6456.         // Add the "Open All in Tabs" menuitem if there are
  6457.         // at least two menuitems with places result nodes.
  6458.         target._endOptOpenAllInTabs = document.createElement("menuitem");
  6459.         target._endOptOpenAllInTabs.setAttribute("oncommand",
  6460.             "PlacesUIUtils.openContainerNodeInTabs(this.parentNode._resultNode, event);");
  6461.         target._endOptOpenAllInTabs.setAttribute("onclick",
  6462.             "checkForMiddleClick(this, event); event.stopPropagation();");
  6463.         target._endOptOpenAllInTabs.setAttribute("label",
  6464.             gNavigatorBundle.getString("menuOpenAllInTabs.label"));
  6465.         target.appendChild(target._endOptOpenAllInTabs);
  6466.     }
  6467.   },
  6468.  
  6469.   fillInBTTooltip: function(aTipElement) {
  6470.     // Fx2XP: Don't show tooltips for bookmarks under sub-folders
  6471.     if (aTipElement.localName != "toolbarbutton")
  6472.       return false;
  6473.  
  6474.     // Fx2XP: Only show tooltips for URL items
  6475.     if (!PlacesUtils.nodeIsURI(aTipElement.node))
  6476.       return false;
  6477.  
  6478.     var url = aTipElement.node.uri;
  6479.     if (!url) 
  6480.       return false;
  6481.  
  6482.     var tooltipUrl = document.getElementById("btUrlText");
  6483.     tooltipUrl.value = url;
  6484.  
  6485.     var title = aTipElement.label;
  6486.     var tooltipTitle = document.getElementById("btTitleText");
  6487.     if (title && title != url) {
  6488.       tooltipTitle.hidden = false;
  6489.       tooltipTitle.value = title;
  6490.     }
  6491.     else
  6492.       tooltipTitle.hidden = true;
  6493.  
  6494.     // show tooltip
  6495.     return true;
  6496.   }
  6497. };
  6498.  
  6499. /**
  6500.  * Drag and Drop handling specifically for the Bookmarks Menu item in the
  6501.  * top level menu bar
  6502.  */
  6503. var BookmarksMenuDropHandler = {
  6504.   /**
  6505.    * Need to tell the session to update the state of the cursor as we drag
  6506.    * over the Bookmarks Menu to show the "can drop" state vs. the "no drop"
  6507.    * state.
  6508.    */
  6509.   onDragOver: function BMDH_onDragOver(event, flavor, session) {
  6510.     session.canDrop = this.canDrop(event, session);
  6511.   },
  6512.  
  6513.   /**
  6514.    * Advertises the set of data types that can be dropped on the Bookmarks
  6515.    * Menu
  6516.    * @returns a FlavourSet object per nsDragAndDrop parlance.
  6517.    */
  6518.   getSupportedFlavours: function BMDH_getSupportedFlavours() {
  6519.     var view = document.getElementById("bookmarksMenuPopup");
  6520.     return view.getSupportedFlavours();
  6521.   },
  6522.  
  6523.   /**
  6524.    * Determine whether or not the user can drop on the Bookmarks Menu.
  6525.    * @param   event
  6526.    *          A dragover event
  6527.    * @param   session
  6528.    *          The active DragSession
  6529.    * @returns true if the user can drop onto the Bookmarks Menu item, false 
  6530.    *          otherwise.
  6531.    */
  6532.   canDrop: function BMDH_canDrop(event, session) {
  6533.     var ip = new InsertionPoint(PlacesUtils.bookmarksMenuFolderId, -1);  
  6534.     return ip && PlacesControllerDragHelper.canDrop(ip);
  6535.   },
  6536.  
  6537.   /**
  6538.    * Called when the user drops onto the top level Bookmarks Menu item.
  6539.    * @param   event
  6540.    *          A drop event
  6541.    * @param   data
  6542.    *          Data that was dropped
  6543.    * @param   session
  6544.    *          The active DragSession
  6545.    */
  6546.   onDrop: function BMDH_onDrop(event, data, session) {
  6547.     // Put the item at the end of bookmark menu
  6548.     var ip = new InsertionPoint(PlacesUtils.bookmarksMenuFolderId, -1);
  6549.     PlacesControllerDragHelper.onDrop(ip);
  6550.   }
  6551. };
  6552.  
  6553. /**
  6554.  * Handles special drag and drop functionality for menus on the Bookmarks 
  6555.  * Toolbar and Bookmarks Menu.
  6556.  */
  6557. var PlacesMenuDNDController = {
  6558.   _springLoadDelay: 350, // milliseconds
  6559.  
  6560.   /**
  6561.    * All Drag Timers set for the Places UI
  6562.    */
  6563.   _timers: { },
  6564.   
  6565.   /**
  6566.    * Called when the user drags over the Bookmarks top level <menu> element.
  6567.    * @param   event
  6568.    *          The DragEnter event that spawned the opening. 
  6569.    */
  6570.   onBookmarksMenuDragEnter: function PMDC_onDragEnter(event) {
  6571.     if ("loadTime" in this._timers) 
  6572.       return;
  6573.     
  6574.     this._setDragTimer("loadTime", this._openBookmarksMenu, 
  6575.                        this._springLoadDelay, [event]);
  6576.   },
  6577.   
  6578.   /**
  6579.    * Creates a timer that will fire during a drag and drop operation.
  6580.    * @param   id
  6581.    *          The identifier of the timer being set
  6582.    * @param   callback
  6583.    *          The function to call when the timer "fires"
  6584.    * @param   delay
  6585.    *          The time to wait before calling the callback function
  6586.    * @param   args
  6587.    *          An array of arguments to pass to the callback function
  6588.    */
  6589.   _setDragTimer: function PMDC__setDragTimer(id, callback, delay, args) {
  6590.     if (!this._dragSupported)
  6591.       return;
  6592.  
  6593.     // Cancel this timer if it's already running.
  6594.     if (id in this._timers)
  6595.       this._timers[id].cancel();
  6596.       
  6597.     /**
  6598.      * An object implementing nsITimerCallback that calls a user-supplied
  6599.      * method with the specified args in the context of the supplied object.
  6600.      */
  6601.     function Callback(object, method, args) {
  6602.       this._method = method;
  6603.       this._args = args;
  6604.       this._object = object;
  6605.     }
  6606.     Callback.prototype = {
  6607.       notify: function C_notify(timer) {
  6608.         this._method.apply(this._object, this._args);
  6609.       }
  6610.     };
  6611.     
  6612.     var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
  6613.     timer.initWithCallback(new Callback(this, callback, args), delay, 
  6614.                            timer.TYPE_ONE_SHOT);
  6615.     this._timers[id] = timer;
  6616.   },
  6617.   
  6618.   /**
  6619.    * Determines if a XUL element represents a container in the Bookmarks system
  6620.    * @returns true if the element is a container element (menu or 
  6621.    *`         menu-toolbarbutton), false otherwise.
  6622.    */
  6623.   _isContainer: function PMDC__isContainer(node) {
  6624.     return node.localName == "menu" || 
  6625.            node.localName == "toolbarbutton" && node.getAttribute("type") == "menu";
  6626.   },
  6627.   
  6628.   /**
  6629.    * Opens the Bookmarks Menu when it is dragged over. (This is special-cased, 
  6630.    * since the toplevel Bookmarks <menu> is not a member of an existing places
  6631.    * container, as folders on the personal toolbar or submenus are. 
  6632.    * @param   event
  6633.    *          The DragEnter event that spawned the opening. 
  6634.    */
  6635.   _openBookmarksMenu: function PMDC__openBookmarksMenu(event) {
  6636.     if ("loadTime" in this._timers)
  6637.       delete this._timers.loadTime;
  6638.     if (event.target.id == "bookmarksMenu") {
  6639.       // If this is the bookmarks menu, tell its menupopup child to show.
  6640.       event.target.lastChild.setAttribute("autoopened", "true");
  6641.       event.target.lastChild.showPopup(event.target.lastChild);
  6642.     }  
  6643.   },
  6644.  
  6645.   // Whether or not drag and drop to menus is supported on this platform
  6646.   // Dragging in menus is disabled on OS X due to various repainting issues.
  6647. //@line 927 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser-places.js"
  6648.   _dragSupported: true
  6649. //@line 929 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser-places.js"
  6650. };
  6651.  
  6652. var PlacesStarButton = {
  6653.   init: function PSB_init() {
  6654.     PlacesUtils.bookmarks.addObserver(this, false);
  6655.   },
  6656.  
  6657.   uninit: function PSB_uninit() {
  6658.     PlacesUtils.bookmarks.removeObserver(this);
  6659.   },
  6660.  
  6661.   QueryInterface: function PSB_QueryInterface(aIID) {
  6662.     if (aIID.equals(Ci.nsINavBookmarkObserver) ||
  6663.         aIID.equals(Ci.nsISupports))
  6664.       return this;
  6665.  
  6666.     throw Cr.NS_NOINTERFACE;
  6667.   },
  6668.  
  6669.   _starred: false,
  6670.   _batching: false,
  6671.  
  6672.   updateState: function PSB_updateState() {
  6673.     var starIcon = document.getElementById("star-button");
  6674.     if (!starIcon)
  6675.       return;
  6676.  
  6677.     var browserBundle = document.getElementById("bundle_browser");
  6678.     var uri = getBrowser().currentURI;
  6679.     this._starred = uri && (PlacesUtils.getMostRecentBookmarkForURI(uri) != -1 ||
  6680.                             PlacesUtils.getMostRecentFolderForFeedURI(uri) != -1);
  6681.     if (this._starred) {
  6682.       starIcon.setAttribute("starred", "true");
  6683.       starIcon.setAttribute("tooltiptext", browserBundle.getString("starButtonOn.tooltip"));
  6684.     }
  6685.     else {
  6686.       starIcon.removeAttribute("starred");
  6687.       starIcon.setAttribute("tooltiptext", browserBundle.getString("starButtonOff.tooltip"));
  6688.     }
  6689.   },
  6690.  
  6691.   onClick: function PSB_onClick(aEvent) {
  6692.     if (aEvent.button == 0)
  6693.       PlacesCommandHook.bookmarkCurrentPage(this._starred);
  6694.  
  6695.     // don't bubble to the textbox so that the address won't be selected
  6696.     aEvent.stopPropagation();
  6697.   },
  6698.  
  6699.   // nsINavBookmarkObserver  
  6700.   onBeginUpdateBatch: function PSB_onBeginUpdateBatch() {
  6701.     this._batching = true;
  6702.   },
  6703.  
  6704.   onEndUpdateBatch: function PSB_onEndUpdateBatch() {
  6705.     this.updateState();
  6706.     this._batching = false;
  6707.   },
  6708.   
  6709.   onItemAdded: function PSB_onItemAdded(aItemId, aFolder, aIndex) {
  6710.     if (!this._batching && !this._starred)
  6711.       this.updateState();
  6712.   },
  6713.  
  6714.   onItemRemoved: function PSB_onItemRemoved(aItemId, aFolder, aIndex) {
  6715.     if (!this._batching)
  6716.       this.updateState();
  6717.   },
  6718.  
  6719.   onItemChanged: function PSB_onItemChanged(aItemId, aProperty,
  6720.                                             aIsAnnotationProperty, aValue) {
  6721.     if (!this._batching && aProperty == "uri")
  6722.       this.updateState();
  6723.   },
  6724.  
  6725.   onItemVisited: function() { },
  6726.   onItemMoved: function() { }
  6727. };
  6728.  
  6729. /**
  6730.  * Various migration tasks.
  6731.  */
  6732. function placesMigrationTasks() {
  6733.   // bug 398914 - move all post-data annotations from URIs to bookmarks
  6734.   // XXX - REMOVE ME FOR BETA 3 (bug 391419)
  6735.   if (gPrefService.getBoolPref("browser.places.migratePostDataAnnotations")) {
  6736.     const annosvc = PlacesUtils.annotations;
  6737.     var bmsvc = PlacesUtils.bookmarks;
  6738.     const oldPostDataAnno = "URIProperties/POSTData";
  6739.     var pages = annosvc.getPagesWithAnnotation(oldPostDataAnno, {});
  6740.     for (let i = 0; i < pages.length; i++) {
  6741.       try {
  6742.         let uri = pages[i];
  6743.         var postData = annosvc.getPageAnnotation(uri, oldPostDataAnno);
  6744.         // We can't know which URI+keyword combo this postdata was for, but
  6745.         // it's very likely that if this URI is bookmarked and has a keyword
  6746.         // *and* the URI has postdata, then this bookmark was using the
  6747.         // postdata. Propagate the annotation to all bookmarks for this URI
  6748.         // just to be safe.
  6749.         let bookmarks = bmsvc.getBookmarkIdsForURI(uri, {});
  6750.         for (let i = 0; i < bookmarks.length; i++) {
  6751.           var keyword = bmsvc.getKeywordForBookmark(bookmarks[i]);
  6752.           if (keyword)
  6753.             annosvc.setItemAnnotation(bookmarks[i], POST_DATA_ANNO, postData, 0, annosvc.EXPIRE_NEVER); 
  6754.         }
  6755.         // Remove the old annotation.
  6756.         annosvc.removePageAnnotation(uri, oldPostDataAnno);
  6757.       } catch(ex) {}
  6758.     }
  6759.     gPrefService.setBoolPref("browser.places.migratePostDataAnnotations", false);
  6760.   }
  6761.  
  6762.   if (gPrefService.getBoolPref("browser.places.updateRecentTagsUri")) {
  6763.     var oldUriSpec = "place:folder=TAGS&group=3&queryType=1" +
  6764.                      "&applyOptionsToContainers=1&sort=12&maxResults=10";
  6765.  
  6766.     var maxResults = 10;
  6767.     var newUriSpec = "place:type=" + 
  6768.                      Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAG_QUERY +
  6769.                      "&sort=" + 
  6770.                      Ci.nsINavHistoryQueryOptions.SORT_BY_LASTMODIFIED_DESCENDING +
  6771.                      "&maxResults=" + maxResults;
  6772.                      
  6773.     var ios = Cc["@mozilla.org/network/io-service;1"].
  6774.               getService(Ci.nsIIOService);
  6775.  
  6776.     var oldUri = ios.newURI(oldUriSpec, null, null);
  6777.     var newUri = ios.newURI(newUriSpec, null, null);
  6778.  
  6779.     let bmsvc = PlacesUtils.bookmarks;
  6780.     let bookmarks = bmsvc.getBookmarkIdsForURI( oldUri, {});
  6781.     for (let i = 0; i < bookmarks.length; i++) {
  6782.       bmsvc.changeBookmarkURI( bookmarks[i], newUri);
  6783.     }
  6784.     gPrefService.setBoolPref("browser.places.updateRecentTagsUri", false);
  6785.   }
  6786. }
  6787. //@line 6190 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  6788.  
  6789. /*
  6790. //@line 40 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser-textZoom.js"
  6791.  */
  6792.  
  6793. // From nsMouseScrollEvent::kIsHorizontal
  6794. const MOUSE_SCROLL_IS_HORIZONTAL = 1 << 2;
  6795.  
  6796. // One of the possible values for the mousewheel.* preferences.
  6797. // From nsEventStateManager.cpp.
  6798. const MOUSE_SCROLL_ZOOM = 3;
  6799.  
  6800. /**
  6801.  * Controls the "full zoom" setting and its site-specific preferences.
  6802.  */
  6803. var FullZoom = {
  6804.  
  6805.   //**************************************************************************//
  6806.   // Name & Values
  6807.  
  6808.   // The name of the setting.  Identifies the setting in the prefs database.
  6809.   name: "browser.content.full-zoom",
  6810.  
  6811.   // The global value (if any) for the setting.  Lazily loaded from the service
  6812.   // when first requested, then updated by the pref change listener as it changes.
  6813.   // If there is no global value, then this should be undefined.
  6814.   get globalValue FullZoom_get_globalValue() {
  6815.     var globalValue = this._cps.getPref(null, this.name);
  6816.     if (typeof globalValue != "undefined")
  6817.       globalValue = this._ensureValid(globalValue);
  6818.     delete this.globalValue;
  6819.     return this.globalValue = globalValue;
  6820.   },
  6821.  
  6822.  
  6823.   //**************************************************************************//
  6824.   // Convenience Getters
  6825.  
  6826.   // Content Pref Service
  6827.   get _cps FullZoom_get__cps() {
  6828.     delete this._cps;
  6829.     return this._cps = Cc["@mozilla.org/content-pref/service;1"].
  6830.                        getService(Ci.nsIContentPrefService);
  6831.   },
  6832.  
  6833.   get _prefBranch FullZoom_get__prefBranch() {
  6834.     delete this._prefBranch;
  6835.     return this._prefBranch = Cc["@mozilla.org/preferences-service;1"].
  6836.                               getService(Ci.nsIPrefBranch2);
  6837.   },
  6838.  
  6839.   // browser.zoom.siteSpecific preference cache
  6840.   siteSpecific: undefined,
  6841.  
  6842.  
  6843.   //**************************************************************************//
  6844.   // nsISupports
  6845.  
  6846.   // We can't use the Ci shortcut here because it isn't defined yet.
  6847.   interfaces: [Components.interfaces.nsIDOMEventListener,
  6848.                Components.interfaces.nsIObserver,
  6849.                Components.interfaces.nsIContentPrefObserver,
  6850.                Components.interfaces.nsISupportsWeakReference,
  6851.                Components.interfaces.nsISupports],
  6852.  
  6853.   QueryInterface: function FullZoom_QueryInterface(aIID) {
  6854.     if (!this.interfaces.some(function (v) aIID.equals(v)))
  6855.       throw Cr.NS_ERROR_NO_INTERFACE;
  6856.     return this;
  6857.   },
  6858.  
  6859.  
  6860.   //**************************************************************************//
  6861.   // Initialization & Destruction
  6862.  
  6863.   init: function FullZoom_init() {
  6864.     // Listen for scrollwheel events so we can save scrollwheel-based changes.
  6865.     window.addEventListener("DOMMouseScroll", this, false);
  6866.  
  6867.     // Register ourselves with the service so we know when our pref changes.
  6868.     this._cps.addObserver(this.name, this);
  6869.  
  6870.     // Listen for changes to the browser.zoom.siteSpecific preference so we can
  6871.     // enable/disable per-site saving and restoring of zoom levels accordingly.
  6872.     this.siteSpecific =
  6873.       this._prefBranch.getBoolPref("browser.zoom.siteSpecific");
  6874.     this._prefBranch.addObserver("browser.zoom.siteSpecific", this, true);
  6875.   },
  6876.  
  6877.   destroy: function FullZoom_destroy() {
  6878.     this._prefBranch.removeObserver("browser.zoom.siteSpecific", this);
  6879.     this._cps.removeObserver(this.name, this);
  6880.     window.removeEventListener("DOMMouseScroll", this, false);
  6881.     delete this._cps;
  6882.   },
  6883.  
  6884.  
  6885.   //**************************************************************************//
  6886.   // Event Handlers
  6887.  
  6888.   // nsIDOMEventListener
  6889.  
  6890.   handleEvent: function FullZoom_handleEvent(event) {
  6891.     switch (event.type) {
  6892.       case "DOMMouseScroll":
  6893.         this._handleMouseScrolled(event);
  6894.         break;
  6895.     }
  6896.   },
  6897.  
  6898.   _handleMouseScrolled: function FullZoom__handleMouseScrolled(event) {
  6899.     // Construct the "mousewheel action" pref key corresponding to this event.
  6900.     // Based on nsEventStateManager::GetBasePrefKeyForMouseWheel.
  6901.     var pref = "mousewheel";
  6902.     if (event.scrollFlags & MOUSE_SCROLL_IS_HORIZONTAL)
  6903.       pref += ".horizscroll";
  6904.  
  6905.     if (event.shiftKey)
  6906.       pref += ".withshiftkey";
  6907.     else if (event.ctrlKey)
  6908.       pref += ".withcontrolkey";
  6909.     else if (event.altKey)
  6910.       pref += ".withaltkey";
  6911.     else if (event.metaKey)
  6912.       pref += ".withmetakey";
  6913.     else
  6914.       pref += ".withnokey";
  6915.  
  6916.     pref += ".action";
  6917.  
  6918.     // Don't do anything if this isn't a "zoom" scroll event.
  6919.     var isZoomEvent = false;
  6920.     try {
  6921.       isZoomEvent = (gPrefService.getIntPref(pref) == MOUSE_SCROLL_ZOOM);
  6922.     } catch (e) {}
  6923.     if (!isZoomEvent)
  6924.       return;
  6925.  
  6926.     // XXX Lazily cache all the possible action prefs so we don't have to get
  6927.     // them anew from the pref service for every scroll event?  We'd have to
  6928.     // make sure to observe them so we can update the cache when they change.
  6929.  
  6930.     // We have to call _applySettingToPref in a timeout because we handle
  6931.     // the event before the event state manager has a chance to apply the zoom
  6932.     // during nsEventStateManager::PostHandleEvent.
  6933.     window.setTimeout(function (self) { self._applySettingToPref() }, 0, this);
  6934.   },
  6935.  
  6936.   // nsIObserver
  6937.  
  6938.   observe: function (aSubject, aTopic, aData) {
  6939.     switch(aTopic) {
  6940.       case "nsPref:changed":
  6941.         switch(aData) {
  6942.           case "browser.zoom.siteSpecific":
  6943.             this.siteSpecific =
  6944.               this._prefBranch.getBoolPref("browser.zoom.siteSpecific");
  6945.             break;
  6946.         }
  6947.         break;
  6948.     }
  6949.   },
  6950.  
  6951.   // nsIContentPrefObserver
  6952.  
  6953.   onContentPrefSet: function FullZoom_onContentPrefSet(aGroup, aName, aValue) {
  6954.     if (aGroup == this._cps.grouper.group(gBrowser.currentURI))
  6955.       this._applyPrefToSetting(aValue);
  6956.     else if (aGroup == null) {
  6957.       this.globalValue = this._ensureValid(aValue);
  6958.  
  6959.       // If the current page doesn't have a site-specific preference,
  6960.       // then its zoom should be set to the new global preference now that
  6961.       // the global preference has changed.
  6962.       if (!this._cps.hasPref(gBrowser.currentURI, this.name))
  6963.         this._applyPrefToSetting();
  6964.     }
  6965.   },
  6966.  
  6967.   onContentPrefRemoved: function FullZoom_onContentPrefRemoved(aGroup, aName) {
  6968.     if (aGroup == this._cps.grouper.group(gBrowser.currentURI))
  6969.       this._applyPrefToSetting();
  6970.     else if (aGroup == null) {
  6971.       this.globalValue = undefined;
  6972.  
  6973.       // If the current page doesn't have a site-specific preference,
  6974.       // then its zoom should be set to the default preference now that
  6975.       // the global preference has changed.
  6976.       if (!this._cps.hasPref(gBrowser.currentURI, this.name))
  6977.         this._applyPrefToSetting();
  6978.     }
  6979.   },
  6980.  
  6981.   // location change observer
  6982.  
  6983.   onLocationChange: function FullZoom_onLocationChange(aURI) {
  6984.     if (!aURI)
  6985.       return;
  6986.     this._applyPrefToSetting(this._cps.getPref(aURI, this.name));
  6987.   },
  6988.  
  6989.   // update state of zoom type menu item
  6990.  
  6991.   updateMenu: function FullZoom_updateMenu() {
  6992.     var menuItem = document.getElementById("toggle_zoom");
  6993.  
  6994.     menuItem.setAttribute("checked", !ZoomManager.useFullZoom);
  6995.   },
  6996.  
  6997.   //**************************************************************************//
  6998.   // Setting & Pref Manipulation
  6999.  
  7000.   reduce: function FullZoom_reduce() {
  7001.     ZoomManager.reduce();
  7002.     this._applySettingToPref();
  7003.   },
  7004.  
  7005.   enlarge: function FullZoom_enlarge() {
  7006.     ZoomManager.enlarge();
  7007.     this._applySettingToPref();
  7008.   },
  7009.  
  7010.   reset: function FullZoom_reset() {
  7011.     if (typeof this.globalValue != "undefined")
  7012.       ZoomManager.zoom = this.globalValue;
  7013.     else
  7014.       ZoomManager.reset();
  7015.  
  7016.     this._removePref();
  7017.   },
  7018.  
  7019.   setSettingValue: function FullZoom_setSettingValue() {
  7020.     var value = this._cps.getPref(gBrowser.currentURI, this.name);
  7021.     this._applyPrefToSetting(value);
  7022.   },
  7023.  
  7024.   /**
  7025.    * Set the zoom level for the current tab.
  7026.    *
  7027.    * Per nsPresContext::setFullZoom, we can set the zoom to its current value
  7028.    * without significant impact on performance, as the setting is only applied
  7029.    * if it differs from the current setting.  In fact getting the zoom and then
  7030.    * checking ourselves if it differs costs more.
  7031.    * 
  7032.    * And perhaps we should always set the zoom even if it was more expensive,
  7033.    * since DocumentViewerImpl::SetTextZoom claims that child documents can have
  7034.    * a different text zoom (although it would be unusual), and it implies that
  7035.    * those child text zooms should get updated when the parent zoom gets set,
  7036.    * and perhaps the same is true for full zoom
  7037.    * (although DocumentViewerImpl::SetFullZoom doesn't mention it).
  7038.    *
  7039.    * So when we apply new zoom values to the browser, we simply set the zoom.
  7040.    * We don't check first to see if the new value is the same as the current
  7041.    * one.
  7042.    **/
  7043.   _applyPrefToSetting: function FullZoom__applyPrefToSetting(aValue) {
  7044.     if (!this.siteSpecific || gInPrintPreviewMode)
  7045.       return;
  7046.  
  7047.     try {
  7048.       if (typeof aValue != "undefined")
  7049.         ZoomManager.zoom = this._ensureValid(aValue);
  7050.       else if (typeof this.globalValue != "undefined")
  7051.         ZoomManager.zoom = this.globalValue;
  7052.       else
  7053.         ZoomManager.zoom = 1;
  7054.     }
  7055.     catch(ex) {}
  7056.   },
  7057.  
  7058.   _applySettingToPref: function FullZoom__applySettingToPref() {
  7059.     if (!this.siteSpecific || gInPrintPreviewMode)
  7060.       return;
  7061.  
  7062.     var zoomLevel = ZoomManager.zoom;
  7063.     this._cps.setPref(gBrowser.currentURI, this.name, zoomLevel);
  7064.   },
  7065.  
  7066.   _removePref: function FullZoom__removePref() {
  7067.     this._cps.removePref(gBrowser.currentURI, this.name);
  7068.   },
  7069.  
  7070.  
  7071.   //**************************************************************************//
  7072.   // Utilities
  7073.  
  7074.   _ensureValid: function FullZoom__ensureValid(aValue) {
  7075.     if (isNaN(aValue))
  7076.       return 1;
  7077.  
  7078.     if (aValue < ZoomManager.MIN)
  7079.       return ZoomManager.MIN;
  7080.  
  7081.     if (aValue > ZoomManager.MAX)
  7082.       return ZoomManager.MAX;
  7083.  
  7084.     return aValue;
  7085.   }
  7086. };
  7087. //@line 6192 "/e/fx19rel/WINNT_5.2_Depend/mozilla/browser/base/content/browser.js"
  7088.  
  7089. HistoryMenu.toggleRecentlyClosedTabs = function PHM_toggleRecentlyClosedTabs() {
  7090.   // enable/disable the Recently Closed Tabs sub menu
  7091.   var undoPopup = document.getElementById("historyUndoPopup");
  7092.  
  7093.   // get closed-tabs from nsSessionStore
  7094.   var ss = Cc["@mozilla.org/browser/sessionstore;1"].
  7095.            getService(Ci.nsISessionStore);
  7096.   // no restorable tabs, so disable menu
  7097.   if (ss.getClosedTabCount(window) == 0)
  7098.     undoPopup.parentNode.setAttribute("disabled", true);
  7099.   else
  7100.     undoPopup.parentNode.removeAttribute("disabled");
  7101. }
  7102.  
  7103. /**
  7104.  * Populate when the history menu is opened
  7105.  */
  7106. HistoryMenu.populateUndoSubmenu = function PHM_populateUndoSubmenu() {
  7107.   var undoPopup = document.getElementById("historyUndoPopup");
  7108.  
  7109.   // remove existing menu items
  7110.   while (undoPopup.hasChildNodes())
  7111.     undoPopup.removeChild(undoPopup.firstChild);
  7112.  
  7113.   // get closed-tabs from nsSessionStore
  7114.   var ss = Cc["@mozilla.org/browser/sessionstore;1"].
  7115.            getService(Ci.nsISessionStore);
  7116.   // no restorable tabs, so make sure menu is disabled, and return
  7117.   if (ss.getClosedTabCount(window) == 0) {
  7118.     undoPopup.parentNode.setAttribute("disabled", true);
  7119.     return;
  7120.   }
  7121.  
  7122.   // enable menu
  7123.   undoPopup.parentNode.removeAttribute("disabled");
  7124.  
  7125.   // populate menu
  7126.   var undoItems = eval("(" + ss.getClosedTabData(window) + ")");
  7127.   for (var i = 0; i < undoItems.length; i++) {
  7128.     var m = document.createElement("menuitem");
  7129.     m.setAttribute("label", undoItems[i].title);
  7130.     if (undoItems[i].image)
  7131.       m.setAttribute("image", undoItems[i].image);
  7132.     m.setAttribute("class", "menuitem-iconic bookmark-item");
  7133.     m.setAttribute("value", i);
  7134.     m.setAttribute("oncommand", "undoCloseTab(" + i + ");");
  7135.     m.addEventListener("click", undoCloseMiddleClick, false);
  7136.     if (i == 0)
  7137.       m.setAttribute("key", "key_undoCloseTab");
  7138.     undoPopup.appendChild(m);
  7139.   }
  7140.  
  7141.   // "Open All in Tabs"
  7142.   var strings = gNavigatorBundle;
  7143.   undoPopup.appendChild(document.createElement("menuseparator"));
  7144.   m = undoPopup.appendChild(document.createElement("menuitem"));
  7145.   m.setAttribute("label", strings.getString("menuOpenAllInTabs.label"));
  7146.   m.setAttribute("accesskey", strings.getString("menuOpenAllInTabs.accesskey"));
  7147.   m.addEventListener("command", function() {
  7148.     for (var i = 0; i < undoItems.length; i++)
  7149.       undoCloseTab();
  7150.   }, false);
  7151. }
  7152.  
  7153. /**
  7154.   * Re-open a closed tab and put it to the end of the tab strip. 
  7155.   * Used for a middle click.
  7156.   * @param aEvent
  7157.   *        The event when the user clicks the menu item
  7158.   */
  7159. function undoCloseMiddleClick(aEvent) {
  7160.   if (aEvent.button != 1)
  7161.     return;
  7162.  
  7163.   undoCloseTab(aEvent.originalTarget.value);
  7164.   getBrowser().moveTabToEnd();
  7165. }
  7166.  
  7167. /**
  7168.  * Re-open a closed tab.
  7169.  * @param aIndex
  7170.  *        The index of the tab (via nsSessionStore.getClosedTabData)
  7171.  */
  7172. function undoCloseTab(aIndex) {
  7173.   // wallpaper patch to prevent an unnecessary blank tab (bug 343895)
  7174.   var tabbrowser = getBrowser();
  7175.   var blankTabToRemove = null;
  7176.   if (tabbrowser.tabContainer.childNodes.length == 1 &&
  7177.       !gPrefService.getBoolPref("browser.tabs.autoHide") &&
  7178.       tabbrowser.selectedBrowser.sessionHistory.count < 2 &&
  7179.       tabbrowser.selectedBrowser.currentURI.spec == "about:blank" &&
  7180.       !tabbrowser.selectedBrowser.contentDocument.body.hasChildNodes() &&
  7181.       !tabbrowser.selectedTab.hasAttribute("busy"))
  7182.     blankTabToRemove = tabbrowser.selectedTab;
  7183.  
  7184.   var ss = Cc["@mozilla.org/browser/sessionstore;1"].
  7185.            getService(Ci.nsISessionStore);
  7186.   if (ss.getClosedTabCount(window) == 0)
  7187.     return;
  7188.   ss.undoCloseTab(window, aIndex || 0);
  7189.  
  7190.   if (blankTabToRemove)
  7191.     tabbrowser.removeTab(blankTabToRemove);
  7192. }
  7193.  
  7194. /**
  7195.  * Format a URL
  7196.  * eg:
  7197.  * echo formatURL("http://%LOCALE%.amo.mozilla.org/%LOCALE%/%APP%/%VERSION%/");
  7198.  * > http://en-US.amo.mozilla.org/en-US/firefox/3.0a1/
  7199.  *
  7200.  * Currently supported built-ins are LOCALE, APP, and any value from nsIXULAppInfo, uppercased.
  7201.  */
  7202. function formatURL(aFormat, aIsPref) {
  7203.   var formatter = Cc["@mozilla.org/toolkit/URLFormatterService;1"].getService(Ci.nsIURLFormatter);
  7204.   return aIsPref ? formatter.formatURLPref(aFormat) : formatter.formatURL(aFormat);
  7205. }
  7206.  
  7207. /**
  7208.  * This also takes care of updating the command enabled-state when tabs are
  7209.  * created or removed.
  7210.  */
  7211. function BookmarkAllTabsHandler() {
  7212.   this._command = document.getElementById("Browser:BookmarkAllTabs");
  7213.   gBrowser.addEventListener("TabOpen", this, true);
  7214.   gBrowser.addEventListener("TabClose", this, true);
  7215.   this._updateCommandState();
  7216. }
  7217.  
  7218. BookmarkAllTabsHandler.prototype = {
  7219.   QueryInterface: function BATH_QueryInterface(aIID) {
  7220.     if (aIID.equals(Ci.nsIDOMEventListener) ||
  7221.         aIID.equals(Ci.nsISupports))
  7222.       return this;
  7223.  
  7224.     throw Cr.NS_NOINTERFACE;
  7225.   },
  7226.  
  7227.   _updateCommandState: function BATH__updateCommandState(aTabClose) {
  7228.     var numTabs = gBrowser.tabContainer.childNodes.length;
  7229.  
  7230.     // The TabClose event is fired before the tab is removed from the DOM
  7231.     if (aTabClose)
  7232.       numTabs--;
  7233.  
  7234.     if (numTabs > 1)
  7235.       this._command.removeAttribute("disabled");
  7236.     else
  7237.       this._command.setAttribute("disabled", "true");
  7238.   },
  7239.  
  7240.   doCommand: function BATH_doCommand() {
  7241.     PlacesCommandHook.bookmarkCurrentPages();
  7242.   },
  7243.  
  7244.   // nsIDOMEventListener
  7245.   handleEvent: function(aEvent) {
  7246.     this._updateCommandState(aEvent.type == "TabClose");
  7247.   }
  7248. };
  7249.  
  7250. /**
  7251.  * Utility class to handle manipulations of the identity indicators in the UI
  7252.  */
  7253. function IdentityHandler() {
  7254.   this._stringBundle = document.getElementById("bundle_browser");
  7255.   this._staticStrings = {};
  7256.   this._staticStrings[this.IDENTITY_MODE_DOMAIN_VERIFIED] = {
  7257.     encryption_label: this._stringBundle.getString("identity.encrypted")  
  7258.   };
  7259.   this._staticStrings[this.IDENTITY_MODE_IDENTIFIED] = {
  7260.     encryption_label: this._stringBundle.getString("identity.encrypted")
  7261.   };
  7262.   this._staticStrings[this.IDENTITY_MODE_UNKNOWN] = {
  7263.     encryption_label: this._stringBundle.getString("identity.unencrypted")  
  7264.   };
  7265.  
  7266.   this._cacheElements();
  7267. }
  7268.  
  7269. IdentityHandler.prototype = {
  7270.  
  7271.   // Mode strings used to control CSS display
  7272.   IDENTITY_MODE_IDENTIFIED       : "verifiedIdentity", // High-quality identity information
  7273.   IDENTITY_MODE_DOMAIN_VERIFIED  : "verifiedDomain",   // Minimal SSL CA-signed domain verification
  7274.   IDENTITY_MODE_UNKNOWN          : "unknownIdentity",  // No trusted identity information
  7275.  
  7276.   // Cache the most recent SSLStatus and Location seen in checkIdentity
  7277.   _lastStatus : null,
  7278.   _lastLocation : null,
  7279.  
  7280.   /**
  7281.    * Build out a cache of the elements that we need frequently.
  7282.    */
  7283.   _cacheElements : function() {
  7284.     this._identityPopup = document.getElementById("identity-popup");
  7285.     this._identityBox = document.getElementById("identity-box");
  7286.     this._identityPopupContentBox = document.getElementById("identity-popup-content-box");
  7287.     this._identityPopupContentHost = document.getElementById("identity-popup-content-host");
  7288.     this._identityPopupContentOwner = document.getElementById("identity-popup-content-owner");
  7289.     this._identityPopupContentSupp = document.getElementById("identity-popup-content-supplemental");
  7290.     this._identityPopupContentVerif = document.getElementById("identity-popup-content-verifier");
  7291.     this._identityPopupEncLabel = document.getElementById("identity-popup-encryption-label");
  7292.     this._identityIconLabel = document.getElementById("identity-icon-label");
  7293.   },
  7294.  
  7295.   /**
  7296.    * Handler for mouseclicks on the "More Information" button in the
  7297.    * "identity-popup" panel.
  7298.    */
  7299.   handleMoreInfoClick : function(event) {
  7300.     displaySecurityInfo();
  7301.     event.stopPropagation();
  7302.   },
  7303.   
  7304.   /**
  7305.    * Helper to parse out the important parts of _lastStatus (of the SSL cert in
  7306.    * particular) for use in constructing identity UI strings
  7307.   */
  7308.   getIdentityData : function() {
  7309.     var result = {};
  7310.     var status = this._lastStatus.QueryInterface(Components.interfaces.nsISSLStatus);
  7311.     var cert = status.serverCert;
  7312.     
  7313.     // Human readable name of Subject
  7314.     result.subjectOrg = cert.organization;
  7315.     
  7316.     // SubjectName fields, broken up for individual access
  7317.     if (cert.subjectName) {
  7318.       result.subjectNameFields = {};
  7319.       cert.subjectName.split(",").forEach(function(v) {
  7320.         var field = v.split("=");
  7321.         this[field[0]] = field[1];
  7322.       }, result.subjectNameFields);
  7323.       
  7324.       // Call out city, state, and country specifically
  7325.       result.city = result.subjectNameFields.L;
  7326.       result.state = result.subjectNameFields.ST;
  7327.       result.country = result.subjectNameFields.C;
  7328.     }
  7329.     
  7330.     // Human readable name of Certificate Authority
  7331.     result.caOrg =  cert.issuerOrganization || cert.issuerCommonName;
  7332.     result.cert = cert;
  7333.     
  7334.     return result;
  7335.   },
  7336.   
  7337.   /**
  7338.    * Determine the identity of the page being displayed by examining its SSL cert
  7339.    * (if available) and, if necessary, update the UI to reflect this.  Intended to
  7340.    * be called by onSecurityChange
  7341.    * 
  7342.    * @param PRUint32 state
  7343.    * @param JS Object location that mirrors an nsLocation (i.e. has .host and
  7344.    *                           .hostname and .port)
  7345.    */
  7346.   checkIdentity : function(state, location) {
  7347.     var currentStatus = gBrowser.securityUI
  7348.                                 .QueryInterface(Components.interfaces.nsISSLStatusProvider)
  7349.                                 .SSLStatus;
  7350.     this._lastStatus = currentStatus;
  7351.     this._lastLocation = location;
  7352.     
  7353.     if (state & Components.interfaces.nsIWebProgressListener.STATE_IDENTITY_EV_TOPLEVEL)
  7354.       this.setMode(this.IDENTITY_MODE_IDENTIFIED);
  7355.     else if (state & Components.interfaces.nsIWebProgressListener.STATE_SECURE_HIGH)
  7356.       this.setMode(this.IDENTITY_MODE_DOMAIN_VERIFIED);
  7357.     else
  7358.       this.setMode(this.IDENTITY_MODE_UNKNOWN);
  7359.   },
  7360.   
  7361.   /**
  7362.    * Return the eTLD+1 version of the current hostname
  7363.    */
  7364.   getEffectiveHost : function() {
  7365.     // Cache the eTLDService if this is our first time through
  7366.     if (!this._eTLDService)
  7367.       this._eTLDService = Cc["@mozilla.org/network/effective-tld-service;1"]
  7368.                          .getService(Ci.nsIEffectiveTLDService);
  7369.     try {
  7370.       return this._eTLDService.getBaseDomainFromHost(this._lastLocation.hostname);
  7371.     } catch (e) {
  7372.       // If something goes wrong (e.g. hostname is an IP address) just fail back
  7373.       // to the full domain.
  7374.       return this._lastLocation.hostname;
  7375.     }
  7376.   },
  7377.   
  7378.   /**
  7379.    * Update the UI to reflect the specified mode, which should be one of the
  7380.    * IDENTITY_MODE_* constants.
  7381.    */
  7382.   setMode : function(newMode) {
  7383.     if (!this._identityBox) {
  7384.       // No identity box means the identity box is not visible, in which
  7385.       // case there's nothing to do.
  7386.       return;
  7387.     }
  7388.  
  7389.     this._identityBox.className = newMode;
  7390.     this.setIdentityMessages(newMode);
  7391.     
  7392.     // Update the popup too, if it's open
  7393.     if (this._identityPopup.state == "open")
  7394.       this.setPopupMessages(newMode);
  7395.   },
  7396.   
  7397.   /**
  7398.    * Set up the messages for the primary identity UI based on the specified mode,
  7399.    * and the details of the SSL cert, where applicable
  7400.    *
  7401.    * @param newMode The newly set identity mode.  Should be one of the IDENTITY_MODE_* constants.
  7402.    */
  7403.   setIdentityMessages : function(newMode) {
  7404.     if (newMode == this.IDENTITY_MODE_DOMAIN_VERIFIED) {
  7405.       var iData = this.getIdentityData();     
  7406.       
  7407.       // It would be sort of nice to use the CN= field in the cert, since that's
  7408.       // typically what we want here, but thanks to x509 certs being extensible,
  7409.       // it's not the only place you have to check, there can be more than one domain,
  7410.       // et cetera, ad nauseum.  We know the cert is valid for location.host, so
  7411.       // let's just use that. Check the pref to determine how much of the verified
  7412.       // hostname to show
  7413.       var icon_label = "";
  7414.       switch (gPrefService.getIntPref("browser.identity.ssl_domain_display")) {
  7415.         case 2 : // Show full domain
  7416.           icon_label = this._lastLocation.hostname;
  7417.           break;
  7418.         case 1 : // Show eTLD.
  7419.           icon_label = this.getEffectiveHost();
  7420.       }
  7421.       
  7422.       // We need a port number for all lookups.  If one hasn't been specified, use
  7423.       // the https default
  7424.       var lookupHost = this._lastLocation.host;
  7425.       if (lookupHost.indexOf(':') < 0)
  7426.         lookupHost += ":443";
  7427.  
  7428.       // Cache the override service the first time we need to check it
  7429.       if (!this._overrideService)
  7430.         this._overrideService = Components.classes["@mozilla.org/security/certoverride;1"]
  7431.                                           .getService(Components.interfaces.nsICertOverrideService);
  7432.  
  7433.       // Verifier is either the CA Org, for a normal cert, or a special string
  7434.       // for certs that are trusted because of a security exception.
  7435.       var tooltip = this._stringBundle.getFormattedString("identity.identified.verifier",
  7436.                                                           [iData.caOrg]);
  7437.       
  7438.       // Check whether this site is a security exception. XPConnect does the right
  7439.       // thing here in terms of converting _lastLocation.port from string to int, but
  7440.       // the overrideService doesn't like undefined ports, so make sure we have
  7441.       // something in the default case (bug 432241).
  7442.       if (this._overrideService.hasMatchingOverride(this._lastLocation.hostname, 
  7443.                                                     (this._lastLocation.port || 443),
  7444.                                                     iData.cert, {}, {}))
  7445.         tooltip = this._stringBundle.getString("identity.identified.verified_by_you");
  7446.     }
  7447.     else if (newMode == this.IDENTITY_MODE_IDENTIFIED) {
  7448.       // If it's identified, then we can populate the dialog with credentials
  7449.       iData = this.getIdentityData();  
  7450.       tooltip = this._stringBundle.getFormattedString("identity.identified.verifier",
  7451.                                                       [iData.caOrg]);
  7452.       if (iData.country)
  7453.         icon_label = this._stringBundle.getFormattedString("identity.identified.title_with_country",
  7454.                                                            [iData.subjectOrg, iData.country]);
  7455.       else
  7456.         icon_label = iData.subjectOrg;
  7457.     }
  7458.     else {
  7459.       tooltip = this._stringBundle.getString("identity.unknown.tooltip");
  7460.       icon_label = "";
  7461.     }
  7462.     
  7463.     // Push the appropriate strings out to the UI
  7464.     this._identityBox.tooltipText = tooltip;
  7465.     this._identityIconLabel.value = icon_label;
  7466.   },
  7467.   
  7468.   /**
  7469.    * Set up the title and content messages for the identity message popup,
  7470.    * based on the specified mode, and the details of the SSL cert, where
  7471.    * applicable
  7472.    *
  7473.    * @param newMode The newly set identity mode.  Should be one of the IDENTITY_MODE_* constants.
  7474.    */
  7475.   setPopupMessages : function(newMode) {
  7476.       
  7477.     this._identityPopup.className = newMode;
  7478.     this._identityPopupContentBox.className = newMode;
  7479.     
  7480.     // Set the static strings up front
  7481.     this._identityPopupEncLabel.textContent = this._staticStrings[newMode].encryption_label;
  7482.     
  7483.     // Initialize the optional strings to empty values
  7484.     var supplemental = "";
  7485.     var verifier = "";
  7486.     
  7487.     if (newMode == this.IDENTITY_MODE_DOMAIN_VERIFIED) {
  7488.       var iData = this.getIdentityData();
  7489.       var host = this.getEffectiveHost();
  7490.       var owner = this._stringBundle.getString("identity.ownerUnknown2");
  7491.       verifier = this._identityBox.tooltipText;
  7492.       supplemental = "";
  7493.     }
  7494.     else if (newMode == this.IDENTITY_MODE_IDENTIFIED) {
  7495.       // If it's identified, then we can populate the dialog with credentials
  7496.       iData = this.getIdentityData();
  7497.       host = this.getEffectiveHost();
  7498.       owner = iData.subjectOrg; 
  7499.       verifier = this._identityBox.tooltipText;
  7500.  
  7501.       // Build an appropriate supplemental block out of whatever location data we have
  7502.       if (iData.city)
  7503.         supplemental += iData.city + "\n";        
  7504.       if (iData.state && iData.country)
  7505.         supplemental += this._stringBundle.getFormattedString("identity.identified.state_and_country",
  7506.                                                               [iData.state, iData.country]);
  7507.       else if (iData.state) // State only
  7508.         supplemental += iData.state;
  7509.       else if (iData.country) // Country only
  7510.         supplemental += iData.country;
  7511.     }
  7512.     else {
  7513.       // These strings will be hidden in CSS anyhow
  7514.       host = "";
  7515.       owner = "";
  7516.     }
  7517.     
  7518.     // Push the appropriate strings out to the UI
  7519.     this._identityPopupContentHost.textContent = host;
  7520.     this._identityPopupContentOwner.textContent = owner;
  7521.     this._identityPopupContentSupp.textContent = supplemental;
  7522.     this._identityPopupContentVerif.textContent = verifier;
  7523.   },
  7524.  
  7525.   hideIdentityPopup : function() {
  7526.     this._identityPopup.hidePopup();
  7527.   },
  7528.  
  7529.   /**
  7530.    * Click handler for the identity-box element in primary chrome.  
  7531.    */
  7532.   handleIdentityButtonEvent : function(event) {
  7533.   
  7534.     event.stopPropagation();
  7535.  
  7536.     if ((event.type == "click" && event.button != 0) ||
  7537.         (event.type == "keypress" && event.charCode != KeyEvent.DOM_VK_SPACE &&
  7538.          event.keyCode != KeyEvent.DOM_VK_RETURN))
  7539.       return; // Left click, space or enter only
  7540.  
  7541.     // Revert the contents of the location bar, see bug 406779
  7542.     handleURLBarRevert();
  7543.  
  7544.     // Make sure that the display:none style we set in xul is removed now that
  7545.     // the popup is actually needed
  7546.     this._identityPopup.hidden = false;
  7547.     
  7548.     // Tell the popup to consume dismiss clicks, to avoid bug 395314
  7549.     this._identityPopup.popupBoxObject
  7550.         .setConsumeRollupEvent(Ci.nsIPopupBoxObject.ROLLUP_CONSUME);
  7551.     
  7552.     // Update the popup strings
  7553.     this.setPopupMessages(this._identityBox.className);
  7554.     
  7555.     // Now open the popup, anchored off the primary chrome element
  7556.     this._identityPopup.openPopup(this._identityBox, 'after_start');
  7557.   }
  7558. };
  7559.  
  7560. var gIdentityHandler; 
  7561.  
  7562. /**
  7563.  * Returns the singleton instance of the identity handler class.  Should always be
  7564.  * used instead of referencing the global variable directly or creating new instances
  7565.  */
  7566. function getIdentityHandler() {
  7567.   if (!gIdentityHandler)
  7568.     gIdentityHandler = new IdentityHandler();
  7569.   return gIdentityHandler;    
  7570. }
  7571.  
  7572. let DownloadMonitorPanel = {
  7573.   //////////////////////////////////////////////////////////////////////////////
  7574.   //// DownloadMonitorPanel Member Variables
  7575.  
  7576.   _panel: null,
  7577.   _activeStr: null,
  7578.   _pausedStr: null,
  7579.   _lastTime: Infinity,
  7580.   _listening: false,
  7581.  
  7582.   //////////////////////////////////////////////////////////////////////////////
  7583.   //// DownloadMonitorPanel Public Methods
  7584.  
  7585.   /**
  7586.    * Initialize the status panel and member variables
  7587.    */
  7588.   init: function DMP_init() {
  7589.     // Load the modules to help display strings
  7590.     Cu.import("resource://gre/modules/DownloadUtils.jsm");
  7591.     Cu.import("resource://gre/modules/PluralForm.jsm");
  7592.  
  7593.     // Initialize "private" member variables
  7594.     this._panel = document.getElementById("download-monitor");
  7595.  
  7596.     // Cache the status strings
  7597.     let (bundle = document.getElementById("bundle_browser")) {
  7598.       this._activeStr = bundle.getString("activeDownloads");
  7599.       this._pausedStr = bundle.getString("pausedDownloads");
  7600.     }
  7601.  
  7602.     gDownloadMgr.addListener(this);
  7603.     this._listening = true;
  7604.  
  7605.     this.updateStatus();
  7606.   },
  7607.  
  7608.   uninit: function DMP_uninit() {
  7609.     if (this._listening)
  7610.       gDownloadMgr.removeListener(this);
  7611.   },
  7612.  
  7613.   /**
  7614.    * Update status based on the number of active and paused downloads
  7615.    */
  7616.   updateStatus: function DMP_updateStatus() {
  7617.     let numActive = gDownloadMgr.activeDownloadCount;
  7618.  
  7619.     // Hide the panel and reset the "last time" if there's no downloads
  7620.     if (numActive == 0) {
  7621.       this._panel.hidden = true;
  7622.       this._lastTime = Infinity;
  7623.  
  7624.       return;
  7625.     }
  7626.   
  7627.     // Find the download with the longest remaining time
  7628.     let numPaused = 0;
  7629.     let maxTime = -Infinity;
  7630.     let dls = gDownloadMgr.activeDownloads;
  7631.     while (dls.hasMoreElements()) {
  7632.       let dl = dls.getNext().QueryInterface(Ci.nsIDownload);
  7633.       if (dl.state == gDownloadMgr.DOWNLOAD_DOWNLOADING) {
  7634.         // Figure out if this download takes longer
  7635.         if (dl.speed > 0 && dl.size > 0)
  7636.           maxTime = Math.max(maxTime, (dl.size - dl.amountTransferred) / dl.speed);
  7637.         else
  7638.           maxTime = -1;
  7639.       }
  7640.       else if (dl.state == gDownloadMgr.DOWNLOAD_PAUSED)
  7641.         numPaused++;
  7642.     }
  7643.  
  7644.     // Get the remaining time string and last sec for time estimation
  7645.     let timeLeft;
  7646.     [timeLeft, this._lastTime] = DownloadUtils.getTimeLeft(maxTime, this._lastTime);
  7647.  
  7648.     // Figure out how many downloads are currently downloading
  7649.     let numDls = numActive - numPaused;
  7650.     let status = this._activeStr;
  7651.  
  7652.     // If all downloads are paused, show the paused message instead
  7653.     if (numDls == 0) {
  7654.       numDls = numPaused;
  7655.       status = this._pausedStr;
  7656.     }
  7657.  
  7658.     // Get the correct plural form and insert the number of downloads and time
  7659.     // left message if necessary
  7660.     status = PluralForm.get(numDls, status);
  7661.     status = status.replace("#1", numDls);
  7662.     status = status.replace("#2", timeLeft);
  7663.  
  7664.     // Update the panel and show it
  7665.     this._panel.label = status;
  7666.     this._panel.hidden = false;
  7667.   },
  7668.  
  7669.   //////////////////////////////////////////////////////////////////////////////
  7670.   //// nsIDownloadProgressListener
  7671.  
  7672.   /**
  7673.    * Update status for download progress changes
  7674.    */
  7675.   onProgressChange: function() {
  7676.     this.updateStatus();
  7677.   },
  7678.  
  7679.   /**
  7680.    * Update status for download state changes
  7681.    */
  7682.   onDownloadStateChange: function() {
  7683.     this.updateStatus();
  7684.   },
  7685.  
  7686.   onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus, aDownload) {
  7687.   },
  7688.  
  7689.   onSecurityChange: function(aWebProgress, aRequest, aState, aDownload) {
  7690.   },
  7691.  
  7692.   //////////////////////////////////////////////////////////////////////////////
  7693.   //// nsISupports
  7694.  
  7695.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIDownloadProgressListener]),
  7696. };
  7697.